python module & package

python module & package

Module

A Python module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.

Modules can define functions, classes, and variables that can be used in other Python programs. By using the import statement, you can include the definitions from a module in your program. This allows you to reuse code across multiple projects, and helps to organize your code into logical units.

For example, consider the following Python module named my_module.py:


def greet(name): print("Hello, " + name + ". How are you today?") def add(a, b): return a + b

You can use the definitions from this module in another Python program like this:


import my_module my_module.greet("John") result = my_module.add(3, 4) print("3 + 4 =", result)

This will produce the following output:

Hello, John. How are you today? 3 + 4 = 7


Package

A Python package is a way to organize related Python modules into a single unit. A package is simply a directory that contains one or more Python modules, along with a special file called __init__.py which tells Python that the directory should be considered a package.

Packages can have sub-packages, which are just packages within packages. This allows for even more organization and separation of related modules.

For example, consider a package named my_package which contains two modules, module1.py and module2.py. The directory structure would look like this:


my_package/ ├── __init__.py ├── module1.py └── module2.py

The __init__.py file can contain initialization code for the package, or it can be empty.

To use the modules in the package, you can import them using dot notation. For example, to use the my_function() function defined in module1.py, you would import it like this:


from my_package.module1 import my_function my_function()

You can also import the entire package or sub-packages using dot notation. For example, to import the entire my_package package, you would use:


import my_package my_package.module1.my_function()

Overall, packages provide a way to organize and structure Python code, making it easier to manage and maintain large projects.

Comments

Popular posts from this blog

Market share of top programming languages python, java

python abstract class

python NumPy - Data science