Writing my_module.py and importing it in 3 steps
A module is created the moment you save a `.py` file. Put a function or class in `my_module.py`, place it next to the file that needs it, and import. Three import forms cover almost every case: `import my_module` (whole module under one name), `from my_module import greet` (one name in your namespace), and `from my_module import greet as g` (renamed).
The import system looks up names in **sys.path**, the list of directories Python searches. The current working directory is on `sys.path` by default, which is why two files in the same folder import each other. When Python imports a module, it runs the file top to bottom once, then caches the result in `sys.modules` so a second import is free.
Star imports like `from my_module import *` pull every public name into the current namespace. Avoid them in coursework. They make the source of any function ambiguous, hide name collisions, and trigger lint warnings on most graders.
# File: my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
# File: main.py
import my_module
from my_module import PI
print(my_module.greet("Alice")) # Hello, Alice!
print(PI) # 3.14159
# Renamed import for clarity in long names
import my_module as mm
print(mm.greet("Bob")) # Hello, Bob!