Learning Python: Modules
In Python, any file that has a py
file extension (a Python file) is considered a module. This allows us to import these modules into other files.
Suppose I have a Python file called user.py
and it contains the following function:
def greeting(): print('Hello!')
We can import all the functions in the user.py
file, including the above function, into another Python file in the following manner:
import user user.greeting()
We can import just the function in the following manner:
from user import greeting greeting()
If we were to move the user.py
file into a users
directory, we would need to create a file called ___init__.py
, which is empty. This tells Python that the directory users
has modules in it. After implementing this, we would import all the functions in the user.py
file in the following manner:
from users import user user.greeting()
We can also just import the greeting
function in the following manner:
from users.user import greeting greeting()
This blog post was originally published on my blog Communicode, where I write about different tech topics.