DEV Community

Cover image for Difference between a python module and a package
Kelvin Wangonya
Kelvin Wangonya

Posted on β€’ Originally published at wangonya.com

5

Difference between a python module and a package

Modules

Modules are single Python files that can be imported. Any python file can be a module. For example, if I have two Python files: module.py and hello.py in the same directory:

# module.py

def hello(name):
    print("Hello {}".format(name))
Enter fullscreen mode Exit fullscreen mode

I can import that module in my hello.py:

#hello.py

import module

module.hello("World!") # Hello World!
Enter fullscreen mode Exit fullscreen mode

The same can be done in the interpreter:

>>> from module import hello
>>> hello("World!") # Hello World!
Enter fullscreen mode Exit fullscreen mode

Packages

Packages are made up of multiple Python files (or modules), and can even include libraries written in different languages like C or C++. Seeing an __init.py__ file in a folder typically tells you that that folder is a Python package. The __init__.py doesn't have to contain any code -- sometimes it does -- it just has to be there for Python take that particular folder as a package.

πŸ“ my_package
    |- __init__.py
    |- module.py
Enter fullscreen mode Exit fullscreen mode
# __init.py__

from my_package.module import hello
Enter fullscreen mode Exit fullscreen mode

When you import my_package in your script, the __init__.py script will be run, giving you access to all of the functions in the package. In this case, it only gives access to the module.hello function.

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

Top comments (2)

Collapse
 
ethancampbell92 profile image
ethancampbell92 β€’

This was a solid difference maker between the two. Appreciate your time putting this article up Kinyanjui.
essay writers uk
London, United Kingdom

Collapse
 
wangonya profile image
Kelvin Wangonya β€’

Glad it helped!

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay