Python Modules vs Packages | Differences Between Python Modules and Packages

Free Python courses with 57 real-time projects - Learn Python

1. Python Modules vs Packages

In our article on Python Modules vs Packages, we discussed what they are, and saw how to create our own. We also saw where they are located in our file system. But throughout the article, we saw a lot of similarities to modules. Hence, we dedicate this article to Differences Between Python Modules and Packages.

Python Modules vs Packages

Python Modules vs Packages

2. What is Python Modules?

A module is a Python file containing Python statements and definitions. For example, a file evenodd.py is a module, and we call it ‘evenodd’. We put similar code together in one module. This helps us modularize our code, and make it much easier to deal with. And not only that, a module grants us reusability. With a module, we don’t need to write the same code again for a new project that we take up.

In our previous article, we created a module evenodd in package two. This is what evenodd.py holds:

def check():
         a=int(input('Enter a number'))
         if a%2==0: print("Even")
         else: print("Odd")

a. How to Import a Python Module?

So, as you can see, a module simply contains Python code. Consequently, we can import it, like a package.

>>> import one.two.evenodd
>>>

To call function check(), we do the following:

>>> from one.two.evenodd import check
>>> check()

Enter a number7
Odd

>>>

Another example would be the constants ‘pi’ and ‘e’ from the ‘math’ module.

>>> import math
>>> from math import pi
>>> math.pi

3.141592653589793

>>> math.e

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

2.718281828459045
We can also import using an alias or using the from..import statement, like we do with packages. To import everything from a module, we do the following:

>>> from math import *
>>> e

2.718281828459045

>>> pi

3.141592653589793

>>>

Let’s update evenodd.py to have two functions- check and evenodd.

def check():
        a=int(input('Enter a number'))
        if a%2==0: print("Even")
        else: print("Odd")
def add(a,b):
        return a+b

Now, if we want to import all functions from module evenodd, we can just use the wildcard *:

>>> from one.two.evenodd import *
>>> check()

Enter a number0
Even

>>> add(3,4)

7

b. Search Path

When we import a module, the interpreter first looks in the current directory. Then, it looks into PYTHONPATH, an environment variable with a list of directories. Finally, it looks into the installation-dependent default directory.

>>> import sys
>>> for i in sys.path:
      print(i)

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\idlelib

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\python36.zip

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\DLLs

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\lib

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\lib\site-packages

c. Reloading a Python Module

A module is imported only once. This is for efficiency purposes. Let’s add this code to evenodd.py:

print("Loading evenodd")
num=7

Now, let’s restart the shell, and import evenodd thrice.

>>> import one.two.evenodd

Loading evenodd

>>> import one.two.evenodd
>>> import one.two.evenodd

See? It imported it only once. Because of this, Python gives us a function to let us reload the module when we want to. This is in the module ‘imp’.

>>> import imp
>>> imp.reload(one.two.evenodd)

Loading evenodd
<module ‘one.two.evenodd’ from ‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\one\\two\\evenodd.py’>

d. dir()

Finally, dir() will let us check the components of a module.

>>> dir(one.two.evenodd)

[‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘add’, ‘check’ , ‘num’]
We saw this function when we talked about the Built-in Functions in Python.

3. What is Python Packages?

A package, in essence, is like a directory holding subpackages and modules. While we can create our own packages, we can also use one from the Python Package Index (PyPI) to use for our projects.

To import a package, we type the following:

import Game.Sound.load

We can also import it giving it an alias:

import Game.Sound.load as load game

You can’t import a function using the dot operator(.) For that, you must type this:

from Game.Sound.load import volume_up

A package must have the file __init__.py, even if you leave it empty.

But when we import a package, only its immediate modules are imported, not the sub-packages. If you try to access those, it will raise an AttributeError.

To get a deeper insight into packages, check Python Packages.

4. Differences Between Python Modules and Packages

So, now that we’ve revised both modules and packages, let’s see how they differ:

  1. A module is a file containing Python code. A package, however, is like a directory that holds sub-packages and modules.
  2. A package must hold the file __init__.py. This does not apply to modules.
  3. To import everything from a module, we use the wildcard *. But this does not work with packages.

This was all about the article on Python Modules vs Packages

5. Conclusion

Now that we know what subtle differences exist between a module and a package, let’s take up a challenge and take up a project of our own. Let’s do this to test our package skills? Okay.

Furthermore, if you have any query, feel free to approach us!

For reference

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

8 Responses

  1. inban says:

    How do create a own module in your pyshell? Then globally how do reach?? ex numpy , pandas

    • Data Flair says:

      Hello Inban,
      That’s an interesting question you’ve got there. Hmm, to create your own module, you need to do the following:
      1. Create a directory
      2. Under that, create two files- __init__.py and calc.py (or name it whatever you want!)
      3. Put all your code inside calc.py
      4. Now, you can import this in the shell with import calc
      Note- You’ll need to get to the location of calc for this to work
      5. Then, you can call functions from calc like you’d from numpy
      We have demonstrated this procedure when we talked of Python Modules.
      https://data-flair.training/blogs/python-modules/
      To really answer your question though, if you want to do all of that right from your shell, keep in mind:
      1. Use the os module to create the calc directory
      2. With os, get into calc, then create and write into the file calc.py
      3. With os, create the __init__.py file
      4. Using os, step out of the calc directory, then import calc as a module
      5. You can now call functions from calc as usual
      Have a nice day, cheers to learning!”

  2. Aravind says:

    can you please help me in understanding the module vs the package vs the library. why does python need them different? Also, inform if any limitations exists for each of them.

    • DataFlair Team says:

      Hello Aravind,
      A Python module is a .py file with function(s) and/or class(es) that you can reuse in your code. You can also create your own.
      A Python package is a directory of such modules. A package often holds modules of a kind together, along with an __init__.py file. You can also create your own, or download the ones on the PyPI.
      The term “”library”” holds no contextual meaning in Python. Loosely described, it is a collection of the core modules; you can call it a package. The standard library, however, is a collection of Python’s syntax, token, and semantics.
      Hope that clears it
      Regards,
      DataFlair

  3. Syed Aqib A says:

    Hello DataFlair Team,
    What is the need of __init__.py file in the Directory? It is automatically get created while I am creating a Directory in Pycharm.

    • DataFlair says:

      The __init__.py file in a directory makes the Python treat files containing the directory as modules which can be imported and used. This is the first file to be loaded in a module.

  4. Laura says:

    Hello, I would like to know how to find which packages are in the standard library of python. Could you help me?

    thanks!

    • DataFlair says:

      Python’s standard library contains over 200 packages. Some of them are context, database, debug, errors. You can access the complte list from the Python’s official documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *