Python Modules
A module is a Python file that has functions, classes or variables you can use in other programs. Modules help you split a big program into small files, and reuse the same code in many places.
Python comes with a lot of ready-made modules (the standard library), like math, random, datetime and os. You can also create your own.
Import a built-in module
Use the import statement, then write the module name, a dot, and the name you want.
import math
print(math.sqrt(25))
print(math.pi)
print(math.ceil(4.2))
print(math.floor(4.8))
5.0
3.141592653589793
5
4
Create your own module
Any Python file can be a module. Save this code in a file named mymodule.py.
# mymodule.py
PI = 3.14
def greet(name):
return "Hello, " + name
Now import it in another file kept in the same folder.
# main.py
import mymodule
print(mymodule.greet("Robin"))
print(mymodule.PI)
Hello, Robin
3.14
from, import and as
from module import nameimports only that name, and you use it without the module name.import module as shortgives the module a short name (alias).from module import *imports everything. Avoid it, because names can clash.
from mymodule import greet
import mymodule as mm
print(greet("Maria"))
print(mm.PI)
Hello, Maria
3.14
The __name__ variable
Every module has a variable __name__. When you run a file directly its value is "__main__". When the file is imported, it is the module name. This lets you keep test code that runs only when the file is run directly.
# greet.py
def hello():
print("Hello")
if __name__ == "__main__":
hello()
Running python greet.py prints Hello. But import greet from another file prints nothing, because __name__ is then "greet".
Packages
A package is a folder that has many modules. Read the difference in module vs package.
shop/
__init__.py
cart.py
payment.py
from shop import cart
from shop.payment import pay
Install modules with pip
Many useful modules are made by other developers. Install them with pip (see virtual environments), then import as normal.
pip install requests
import requests
Where does Python look for modules?
Python searches the current folder first, then the folders from PYTHONPATH, then the standard library and installed packages. You can see the list with sys.path.
import sys
print(sys.path)
Summary
- A module is a
.pyfile. Useimportto use it. - Use
fromto import one name andasto give a short name. - Use
if __name__ == "__main__":for code that should run only when the file is run directly. - A package is a folder of modules.
- Install outside modules with
pip.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |