How to Write a Python Module/Package?

In this article, we will learn about modules and packages in Python. We will look at the different ways to import these modules and packages and run the function outside the same module.

What is a module?

In lay man’s terms the file within which the Python code resides is known as a module. It consists of functions, variables and classes (basically,everything that can be included within the code) and generally has the .py extension. It becomes easy to organize the Python code by using modules. Modules allow coders to group the related code thereby making the code easier to use as it is structured/organized.

How to Import a Module in Python?

The import statement is used to fetch and use (import) the contents of code from one Python module into another.

Syntax: import module_name

Example: Let’s say, there’s a file in the current directory named module1.py and it contains the following code:

def fun():
    print("Hello World!")

You can import the module1.py module from the current directory with the help of the import statement as shown below.

import test

Let’s have a quick look at what the official documentation says about the import statement in Python:

How to Call a Function from Another File in Python?

Method 1: Import the Entire Module

You can simply use the import statement to import the entire module into another Python file and then use the dot notation to fetch a particular fucntion from the imported module into the current Python file.

Example: In the following example we will import the fun() method from module1.

>>> import module1
>>> module1.fun()
# Hello World!

Method 2: Using from Module_Name import Function_Name

You can use the “from module import function” statement specific functions from a Python module instead of importing the entire module. The following example demonstrates how you can use this statement to import the funtion fun() from the module – module1.

>>> from module1 import fun
>>> fun()
# Hello World!

Let’s consider another example where you can use the from…import… statement to import the pi method of the math module in Python.

from math import pi
print(pi)

# 3.141592653589793

Note: You don’t have to prefix “pi” with “math” in this case, since only the “pi” method has been imported and not the entire math module.

Method 3: Using from Module_Name import *

In case you do not wish to prefix every method with the module name you can use the “from module_name import *” statement. However, in this case all the members icluding variables and functions (entire module) get imported.

Example:

from math import *
print(pi)
print(cos(45))

# 3.141592653589793 
# 0.5253219888177297

Now that you already know how to import functions of a specific module, let’s have a quick look at how you can use the above methods to import member variables of a given module into another Python code.

Example: Consider the following module- test.py:

student1 = {
  "name": "ABC",
  "age": 20,
  "roll_no": "2"
}

Let’s import specific variables of the above module in another Python code.

Method 1

>>> import test
>>> x = test.student1[" age"]
>>> y = test.student1[" name"]
>>> z = test.student1[" roll_no"]
>>> print("Age -", x)
>>> print("Name -", y)
>>> print("Roll no -", z)

# Age - 20
# Name - ABC
# Roll no - 2

Method 2

>>> from test import student1
>>> print("Age -", student1[" age"])
>>> print("Name -", student1[" name"])
>>> print("Roll no -", student1[" roll_no"])

# Age - 20
# Name - ABC
# Roll no - 2

Packages in Python

Like modules are used to store files similarly packages are used to store the directories. If we have to write an application that has large code snippets, it becomes easier to put those codes in the module and the different modules inside the different packages. A single Python package can have different sub-packages and modules.

Installing the packages

You can install the packages by using the following commands:

python setup.py installAfter using this command, it will install the package in the site-packages directory of the current Python distribution. The packages can then be used in any Python file by running only the import command: import project
python setup.py develop◉ After using this command, it will install the links to the current package source code in the site-packages directory of the current Python distribution. The packages can then be imported in any Python file using: import project.
◉ You can also use the –user option to install the current user site-packages directory.

Example: Suppose there’s a folder in the current directory named package1.py and it contains a module1.py and an empty file (__init__.py). Let’s say that module1.py contains the following code:

def fun():
    print(" Hello World! ")

We can import this function from the package and run it in different ways using the Python interpreter:

Importing the Entire Package

>>> import package1
>>> from package1 import module1
>>> module1.fun()
# Hello World!

Importing a Module from The Package

>>> import package1.module1
>>> package1.module1.fun()
# Hello World!

Importing a Method from a Module of The Package

>>> from package1.module1 import fun
>>> fun()
# Hello World!

❒Importing a Specific Module from The Package

>>> from package1 import module1
>>> module1.fun()
# Hello World!

Relative Imports

In case of relative imports, the module’s name is searched in the packages to determine where the module can be used.

>>> If __name__	==	"module1":
>>> from 	. import	fun
Hello World!

Note: The __name__ must have atleast as many dots as there are in the import statement. If __name__ has zero dots (“__main__”), then you will get an error: “Error: relative-import in non-package“.

POINTS TO NOTE

  • You can also group many different .py extension files by putting them in the same folder. In python, the folder is considered as a package only if it consists of a file named __init__.py. Suppose you have two packages:
  • package1 folder consists of two modules: module1.py and module2.py and package2 folder consists of modules: __init__.py, module1.py, and module2.py and also consist of a subpackage1 with module3.py and __init__.py
  • Here, package1 modules cannot be accessed from the root directory using package1.module1 as it does not contain __init__.py. However, package2 modules can be accessed from the root directory using package2.module1 as it contains __init__.py. You can also access subpackage1 modules using package2. subpackage1.module3.

💎Difference between Modules and Packages

ModulesPackages
A module is a file containing Python definitions, variables, classes, definitions, and functions.The package is a folder of all the modules and sub-packages in Python.
All modules generally have a .py extension.The package folder should consist of an __init__.py file even if it is empty.
We can use the wildcard * to import everything from the module.We cannot use the wildcard * directly, to import everything from the package.

Conclusion

In this article, we learned about modules and packages in Python. We looked at the different methods to import a module and package, and the differences between them. I hope you found this article to be helpful! Please stay tuned and subscribe for more tutorials and discussions.

🎓 Post Credits: SHUBHAM SAYON and RASHI AGARWAL


Recommended Course:

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
The Complete Guide to PyCharm
Join the PyCharm Masterclass now, and master PyCharm by tomorrow!