Modules in Python
In Python, a module is a file containing Python code. This file may include function definitions, variables, classes, and executable statements that can be used in an application. Modules allow you to organize your code into separate files, making it easier to manage and reuse code across different programs.
Here's a brief overview of how modules work in Python:
- Creating a Module:
- Importing Modules:
- Importing Specific Classes, Variables, and Functions:
- Using Variables and Functions:
- Standard Library Modules:
To create a module, simply create a Python script (a .py file) that contains your code. For example, if you want to create a module for some utility functions, you can create a file named my_module.py and add some functions as shown in the example below:
def add(a, b): result = a + b return result def substract(a, b): result = a - b return result
To use the functions, classes, or variables defined in a module, you need to import the module into your Python script. This is typically done using the import statement.
import my_module x = my_module.add(10, 40) y = my_module.substract(10, 5) print(x) print(y)
You can also use an alias for the module by importing it with a different name, using the "as" keyword during the import:
import my_module as md x = md.add(10, 40) y = md.substract(10, 5) print(x) print(y)
If you only need specific functions, classes, or variables from a module, you can import them directly without importing the entire module, using the "from" keyword.
import add, substract from my_module x = add(10, 40) y = substract(10, 5) print(x) print(y)
After a module is imported, you can access its functions, classes, and variables using dot "." notation.
import my_module variable_value = my_module.my_variable result = my_module.my_function()
Python also comes with a vast standard library of modules that provide various functionalities, such as math, os, datetime, and many more. These can be imported and used in your programs as needed.
Here's an example of a built-in function in Python, len(), which returns the length of a string, array, tuple, list, or dictionary:
x = "Hello Buddy" y = [11,23,54,74,54] x_length = len(x) y_length = len(y) print(x) print(y)