Small scripts fit in one file. Real projects do not. Python organises code into modules (single .py files) and packages (folders of modules). Understanding how import works saves a lot of confusing errors.
Modules
Any .py file is a module. If you have pricing.py with a function add_tax(), another file in the same folder can use it:
import pricing
pricing.add_tax(100)
from pricing import add_tax
add_tax(100)
The first style keeps the module name visible, which makes it clear where a function came from. Avoid from pricing import *: it hides where names come from and can silently overwrite your own variables.
Packages
A package is a folder containing modules, usually with an __init__.py file. For example shop/pricing.py and shop/orders.py can be imported as from shop.pricing import add_tax. Django apps are packages, which is why you see imports like from .models import Course, where the dot means “this package”.
Where Python looks
When you import, Python searches the folder of the script you ran, then installed libraries, using the list in sys.path. Two common mistakes follow from this:
- Naming your file after a library. A file called
random.pyorpandas.pyin your project will be imported instead of the real library. - Running a file from the wrong folder, so Python cannot see your package.
The if __name__ == “__main__” check
Code at the top level of a module runs whenever it is imported. Put test or demo code under if __name__ == "__main__": so it runs only when you execute the file directly, not when another file imports it.
Circular imports
If a.py imports b.py and b.py imports a.py, you may get an ImportError. The usual fix is to move the shared code into a third module that both can import.
Related: Python virtual environments and Python functions for beginners.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
