Skip to content

Package in Python

Package in Python

Package in Python is a place where we can store same type of multiple modules . When we write many modules, our program becomes very big. Then we put the similar type of module in one place and different type of module in another place. That place is the package in Python. Any Python package can have other types of files besides .py file (e.g. .txt file etc.). Also a Python package can have sub-package and sub-sub-package in it. Each Python package must have a __init__.py file so that Python understands that it is a package.

The figure above shows the structure of a package in Python . package1 is a package containing three files and a folder. The three files are __init__.py, module1.py and module2.py and the folder is a sub-package named subpackage1, which contains two more files __init__.py and module3.py. The contents of all the files are given below. We will keep package1 in the folder in which we are working now.

#package1
#__init__.py
print("importing package1")
#package1
#module1.py
def add(a,b):
    return a+b

def factorial(a):
    fact=1
    for i in range(1,a+1):
        fact*=i
    return fact
#package1
#module2.py
def greet(name):
    print(f"hello {name}")

def product(a,b):
    return a*b
#package1/subpackage1
#__init__.py
print("importing subpackage1")
#package1/subpackage1
#module3.py
def sub(a,b):
    return a-b

s=10

Note :

__init__.py file is the initializer file. This file is automatically executed whenever a package is imported.

The from – import statement in Python

Importing multiple modules from a package

With this statement one or more modules can be imported from any package.

Syntax

from package-name import module1 , module2

Example 1:

# importing module1 from package1
from package1 import module1

# calling the add() from module1
print(module1.add(4,5))
importing package1
9

In the above code, module1 have been imported from package1 . Since it has been imported from package1, the __init__.py file of package1 has been automatically executed which has printed importing package1. Then the add() function of module1 is called which returns 9.

Example 2:

# importing module3 from subpackage1
from package1.subpackage1 import module3

# calling the sub() from module3
print(module3.sub(5,3))
importing package1
importing subpackage1
2

In the above code, module3 has been imported from package1.subpackage1. Since it has been imported from package1.subpackage1 , the __init__.py file of both package1 and subpackage1 has been automatically executed which has printed importing package1 and importing subpackage1. Then the sub() function of module3 is called which returns 2.

Importing multiple names from a module of a package

This statement also allows us to import one or more names from any module in a package.

Syntax

from package_name.module_name import name1 , name2

Example 1:

# importing factorial function from module1 of package1
from package1.module1 import factorial
print(factorial(5))
importing package1
120

In the above code, factorial() function has been imported from module1 of package1. Since it has been imported from package1, the __init__.py file of package1 has been automatically executed which has printed importing package1. Then the factorial() function of module1 is called which returns 120.

Example 2:

# importing s variable from module3 of subpackage1
from package1.subpackage1.module3 import s
print(s)
importing package1
importing subpackage1
10

In the above code, s variable has been imported from module3 of package1.subpackage1. Since it has been imported from package1.subpackage1, the __init__.py file of package1 and subpackage1 has been automatically executed which has printed importing package1 and importing subpackage1. Then the s variable of module3 is printed which returns 10.

Importing the entire package

An entire package can also be imported with the help of this statement.

Syntax

from package_name import *

Example 1:

# importing entire package1
from package1 import *
print(module1.add(4,5))
importing package1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_8956/896924682.py in <module>
      1 # importing entire package1
      2 from package1 import *
----> 3 print(module1.add(4,5))

NameError: name 'module1' is not defined

In the above code, first package1 has been imported which has printed importing package1. Then the add() function of module1 was called which showed error. Error showing that name 'module1' is not defined .

Checking if the names of any package in the current local scope or not

With the built-in dir() function we can check if the names of the package1 is in the current local scope or not . The dir() function will return a list of all names in the current local scope .

from package1 import *
print(dir())
importing package1
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'quit']

From the output of the above code we can see that module1 name of package1 is not in the current local scope. For this reason the previous program showed error. The package1 we have created has three names module1, module2 and subpackage1. Now these three names need to be added to our package1 dir list.

Adding the names of any package in the current local scope

For that we will write the list [module1, module2, subpackage1] in the __init__.py file of package1 using __all__ keyword , which will add the new names of package1 to the package1 dir list. Similarly, using the __all__ keyword, we will write the [module3] list in the __init__.py file of subpackage1, which will add the module3 name of subpackage1 to the subpackage1 dir list.

Modified __init__.py file of both pakage1 and subpackage1 is shown below

#package1
#__init__.py
print("importing package1")


#to add all the name in dir list
__all__ = ["module1","module2","subpackage1"]
#package1/subpackage1
#__init__.py
print("importing subpackage1")

#to add all the name in dir list
__all__ = ["module3"]

Now if we call the dir() function then we can see that all the names of package1 have been added to the dir list.

from package1 import *
print(dir())
importing package1
importing subpackage1
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'module1', 'module2', 'quit', 'subpackage1']

In the above code, since everything has been imported from package1, both __init__.py file of package1 and subpackage1 have executed , and in the dir list we can see all the names of package1.

Now let’s again run the program of Example 1

# importing entire package1
from package1 import *
print(module1.add(4,5))
importing package1
importing subpackage1
9

In the above code, the add() function of module1 will run and return 9.

Example 2:

# importing entire subpackage1
from package1.subpackage1 import *
print(module3.s)
importing package1
importing subpackage1
10

In the above code, everything has been imported from package1‘s subpackage1. Then the s variable of module3 has been printed which has printed 10.

Note :

We can use package_name.module_name during import but we cannot use package_name.module_name after import.

Example :
# importing entire package1
from package1 import *
print(subpackage1.module3.s)
importing package1
importing subpackage1
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_9536/1975643803.py in <module>
      1 # importing entire package1
      2 from package1 import *
----> 3 print(subpackage1.module3.s)

AttributeError: module 'package1.subpackage1' has no attribute 'module3'

In the above code as we have used subpackage1.module3 after importing package1, the program has raised an error

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply