Any .py file you write is a module, and you can import it from another file just like math or random. This way you can split a big program into small pieces and reuse the same functions in different projects.
Your own module
Imagine you save this file with the name geometry.py:
# geometry.py
PI = 3.14159
def circle_area(radius):
return PI * radius ** 2
def rectangle_area(base, height):
return base * height
And in another file, in the same folder, you import it:
# main_program.py
import geometry
print(geometry.circle_area(2)) # 12.56636
print(geometry.rectangle_area(3, 4)) # 12
# or
from geometry import rectangle_area
print(rectangle_area(5, 2)) # 10
The file name (without .py) is the module name, so it must be a valid identifier: no spaces or hyphens and not starting with a number. Do not give it the same name as a standard module (for example math.py or random.py), because it would hide the original.
The problem: code that runs on import
When you import a module, Python runs the whole file. If the module contains "loose" code, for example a print, it will run on every import:
# geometry.py
def circle_area(radius):
return 3.14159 * radius ** 2
print(circle_area(1)) # it also runs when doing import geometry!
The solution: if __name__ == "__main__"
Python stores the name of the module in the variable __name__. When you launch a file directly, __name__ is "__main__"; when someone imports it, it is the module name. With that condition the test code only runs when you launch the file:
# geometry.py
def circle_area(radius):
return 3.14159 * radius ** 2
def main():
print(circle_area(1))
if __name__ == "__main__":
main()
- If you run
python geometry.py,main()is called. - If you do
import geometryfrom another file, only the functions are defined and nothing else runs.
It is the usual way to structure a program: functions at the top, a main() function with the main logic and this condition at the end.
Packages
A folder with several related modules is called a package. It is imported with dot notation:
# structure
# utilities/
# text.py
# numbers.py
from utilities import numbers
from utilities.text import clean
Where Python looks for modules
When you do import something, Python looks for it in this order: the folder of the program being run, the standard library and the packages installed with pip. If the file is not in any of those places, you get a ModuleNotFoundError.
Practice in Reusable functions.