Lesson 38 / 47
Imports & Your Own Modules
Split code across files and reuse it with import.
import styles
Any .py file is a module. import brings its names in; from ... import ... brings specific names directly.
# mathutils.py
def add(a, b):
return a + b
# main.py
import mathutils
from mathutils import add as add_numbers
print(mathutils.add(2, 3))
print(add_numbers(2, 3))__name__ == "__main__"
if __name__ == "__main__": guards code that should run only when the file is executed directly — not when it's imported by another file.
def main():
print("Running as a script")
if __name__ == "__main__":
main()Packages
A package is a folder of modules with an __init__.py file, letting you organize related code under one import path like myapp.utils.