Understanding Python Modules: Creation, Usage, and Import Techniques
What Is a Python Module?
In Python programming, a module functions as a reusable code library. Essentially, it is a file that contains a collection of functions, variables, and classes designed to be included in your application to extend its capabilities.
How to Create a Python Module
Creating a module is straightforward: simply save your Python code within a file that uses the .py
extension. This file then becomes a module that you can import into other Python scripts.
# Example: Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Using a Python Module
After creating a module, you can access its functions or variables by importing it using the import
statement. For example:
import mymodule
mymodule.greeting("Jonathan")
Note that when calling a function from a module, the syntax follows the pattern module_name.function_name()
.
Variables Within a Module
Modules are not limited to functions; they can also contain variables of various types such as dictionaries, lists, and objects.
# Example: Define a dictionary in mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Accessing this dictionary after importing the module:
import mymodule
age = mymodule.person1["age"]
print(age)
Naming and Renaming Modules
Modules must be saved with a .py
extension but the filename itself can be anything meaningful to your project. Furthermore, when importing a module, you may assign it an alias using the as
keyword to simplify references:
import mymodule as mx
age = mx.person1["age"]
print(age)
Exploring Python’s Built-in Modules
Python offers numerous built-in modules that provide additional functionality. For example, the platform
module lets you retrieve information about the operating system:
import platform
os_name = platform.system()
print(os_name)
Listing Module Contents with dir()
To inspect all functions and variables defined within a module, use the built-in dir()
function:
import platform
contents = dir(platform)
print(contents)
This method is applicable to all modules, including those you create yourself.
Selective Import Using from
Keyword
If you only need specific components from a module, the from
statement allows selective importing:
# In mymodule.py
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
# In your main script
from mymodule import person1
print(person1["age"])
When using selective import, you can directly reference the imported elements without prefixing them with the module name.