In Python, modules are simply files containing Python definitions, statements, and functions. You can think of a module as a library that can be imported and used in other Python scripts or modules. Python also allows you to group related modules into a package.
Here’s an example of a Python module:
# mymodule.py def hello(name): print(f"Hello, {name}!") def goodbye(name): print(f"Goodbye, {name}!")
This module contains two functions: hello()
and goodbye()
. These functions can be imported and used in other Python scripts.
To use a module in your Python script, you need to import it. Here’s an example of how to import the mymodule
module and call its functions:
import mymodule mymodule.hello("John") mymodule.goodbye("John")
This will output:
Hello, John! Goodbye, John!
In addition to importing the entire module, you can also import specific functions or attributes from a module using the from
keyword. For example:
from mymodule import hello hello("Jane")
This will output:
Hello, Jane!
Packages, on the other hand, are simply directories containing Python modules. A package must contain a special file called __init__.py
, which tells Python that this directory should be treated as a package.
Here’s an example of a Python package:
my_package/ __init__.py module1.py module2.py
To import a module from a package, you can use dot notation. For example:
import my_package.module1 my_package.module1.function1()
This will call the function1()
function from the module1
module inside the my_package
package.