Every
.py file is a module. Splitting one big script into several small files keeps each piece focused. You write the helper code in helpers.py, then pull it into your main program with an import statement.Creating and importing modules
# write the module file
with open('helpers.py', 'w') as f:
f.write("def greet(name):\n return f'Hello, {name}!'\n")
# tell Python to forget its old search results
import importlib
importlib.invalidate_caches()
# now import it like any other module
from helpers import greetThe __name__ guard
When your program is the one being run directly, its name is
'__main__'. When it is imported by another file, its name is just the filename without .py, for example helpers. That difference lets you write code that only runs when a module is executed on its own.# inside helpers.py
def greet(name):
return f'Hello, {name}!'
if __name__ == '__main__':
# runs only when helpers.py itself is run
print(greet('world'))Packages and inspection tools
A package is a folder that contains an
__init__.py file (it can be empty). os.makedirs('shop', exist_ok=True) creates the folder (exist_ok=True means no error if it is already there), and then you import from inside it with a dot: from shop.pricing import total.import os, importlib
os.makedirs('shop', exist_ok=True)
# an empty __init__.py: open it, write nothing
with open('shop/__init__.py', 'w') as f:
pass
with open('shop/pricing.py', 'w') as f:
f.write('def total(prices):\n')
f.write(' return sum(prices)\n')
importlib.invalidate_caches()
from shop.pricing import total
print(total([2, 3])) # 5To see what a module offers,
dir() lists its names: after import math, print(dir(math)) shows pi, sqrt and the rest. When you import, Python searches a list of folders, sys.path, in order, starting with the folder your code runs in. That is how it finds your own helpers.py.