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.

Python
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.