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__':
print(greet('world')) # runs only if you do: python helpers.pyPackages 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, and then you import from inside it with a dot: from shop.pricing import total.import os, importlib
os.makedirs('shop', exist_ok=True)
open('shop/__init__.py', 'w').close() # an empty __init__.py
with open('shop/pricing.py', 'w') as f:
f.write("def total(prices):\n return sum(prices)\n")
importlib.invalidate_caches()
from shop.pricing import total
print(total([2, 3])) # 5To see what a module offers,
dir(module) lists its names. Python looks for modules in the folders listed in sys.path, in order.