Lesson 70 +10 XP

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:


python

### mymodule.py
def greeting(name):
    print("Hello, " + name)

person1 = {
    "name": "John",
    "age": 36,
    "country": "Norway"
}

Use it with import


python
import mymodule

mymodule.greeting("Jonathan")

### Hello, Jonathan
print(mymodule.person1["age"])

### 36

The from keyword

Import specific names:


python
from mymodule import person1
print(person1["age"])

### 36

Import with an alias


python
import mymodule as mx
mx.greeting("Ada")

From with alias


python
from mymodule import person1 as p
print(p["age"])

List a module's names

dir() shows everything a module contains:


python
import platform
print(dir(platform))

Built-in modules

Python ships with many, like platform:


python
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 module or from module import name.
  • Aliases: import module as m.
  • dir() lists a module's names.
  • Python has many built-in modules.