Show List

Python Modules and Packages

In Python, a module is a single file that contains code, while a package is a collection of modules in directories that give a package hierarchy.

Modules in Python allow you to organize and reuse code. By dividing your code into separate modules, you can make your code more organized, easier to understand, and easier to maintain.

Here is an example of how to create and use a Python module:

python
Copy code
# my_module.py def say_hello(): print("Hello from the module") # main.py import my_module my_module.say_hello()

In this example, my_module.py is a module that defines a function say_hello(). The main.py file then imports this module and calls the say_hello() function.

Packages in Python allow you to further organize your modules into a directory structure. For a directory to be recognized as a Python package, it must contain a file named __init__.py. This file can be empty, but its presence tells Python that the directory should be considered as a package.

Here is an example of how to create and use a Python package:

python
Copy code
# my_package/ # __init__.py # my_module.py # main.py # my_package/__init__.py # my_package/my_module.py def say_hello(): print("Hello from the package") # main.py import my_package.my_module my_package.my_module.say_hello()

In this example, my_package is a package that contains a module my_module.py. The main.py file then imports this module and calls the say_hello() function.


    Leave a Comment


  • captcha text