Loading lessons...
Modules
Modules
A module is a Python file with code you can reuse. Import it and use its functions and variables.
Make a module
Save a file with functions and variables:
# mymodule.py
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Use it with import
import mymodule
mymodule.greeting("Jonathan") # Hello, Jonathan
print(mymodule.person1["age"]) # 36
The from keyword
Import specific names:
from mymodule import person1
print(person1["age"]) # 36
Import with an alias
import mymodule as mx
mx.greeting("Ada")
From with alias
from mymodule import person1 as p
print(p["age"])
List a module's names
dir() shows everything a module contains:
import platform
print(dir(platform))
Built-in modules
Python ships with many, like platform:
import platform
x = platform.system()
print(x) # e.g. Windows
The builtins module
import builtins exposes the built-in functions themselves. Generally you don't need to import it; they're always available.
TL;DR
- A module is a .py file of reusable code.
import moduleorfrom module import name.- Aliases:
import module as m. dir()lists a module's names.- Python has many built-in modules.