8. Modules and packages¶
To understand what a Python module is, new folder create a file named "mymodule.py" with the following content:
def myfun(x): print(x) myvar = 231.32
Now open your Python interpreter in that folder and run:
import mymodule mymodule.myfun("hi there") mymodule.myvar
As you can see, you are able to access the variables and functions defined in the after importing it. You can also import the module and give it another name for simplicity:
import mymodule as mym mym.myfun("hi there") mym.myvar
You can also import a specific object of a module:
from mymodule import myfun myfun("hi there")
And you can even give it another name:
from mymodule import myfun as another_name_for_this_fun another_name_for_this_fun("hi there")
Although not recommend, you can also import all the objects of this module using
from mymodule import * myfun("hi there") myvar
In general, this should be avoided because it makes your code less readable and can cause unpredictable results as having multiple packages importing variables with the same name and thus overriding each other.
A package is a folder containing an
__init__.py file and (possibly) modules as well, we will not go into details of how to create one for now.
More importantly, you can install packages on your system from your system package manager (example: on Ubuntu/Debian, you can install the package using
apt-get install python3-numpy) or using
pip3 depending on the system):
pip install numpy --user
After that, you should be able to call:
import numpy as np
On your Python interpreter.