What is a Module?
A module is easiest to picture as a code library: a single file that holds a set of functions you would like to bring into your application.
Create a Module
There is nothing special to set up. Put the code in a file whose name ends in .py and you have a module:
Example
mymodule.pydef greeting(name):
print("Hello, " + name)
Use a Module
With the file saved, the import statement brings the module into your program:
Note: To call one of its functions, write the module name, a dot, and the function name: module_name.function_name.
Example
mymodule and call the greeting function with the argument "Jonathan".
The module contains a function greeting(name) that prints "Hello, " + name.
Output: complete Python program
import mymodule
mymodule.greeting("Jonathan")
Variables in Module
Functions are not the only thing a module can hold. It can also store variables of any type, such as lists, dictionaries and objects:
Example
mymodule and access the person1 dictionary's "age" key.
Print the age value.
Output: complete Python program
import mymodule
a = mymodule.person1["age"]
print(a)
Example
mymodule.pyperson1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Naming a Module
The file name is entirely up to you, as long as it ends with the .py extension.
Re-naming a Module
The as keyword lets you give a module a different name, an alias, at the moment you import it:
Example
mymodule by the alias mx:mymodule with the alias mx.
Access person1["age"] through the alias and print it.
Output: complete Python program
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
Python ships with a number of modules of its own, ready to import at any time.
Example
platform module and call one of its functions:platform module.
Use platform.system() to get the system name and print it.
Output: complete Python program
import platform
x = platform.system()
print(x)
Using the dir() Function
To see what a module offers, call the built-in dir() function, which lists the names of all its functions and variables:
Note: dir() works on every module, including those you write yourself.
Example
platform module.
Use the dir() function to list all names in the platform module and print the result.
Output: complete Python program
import platform
x = dir(platform)
print(x)
Import From Module
When you need just one piece of a module, the from keyword lets you import that piece alone.
Note: Items imported with from are used without the module prefix. Write person1["age"], not mymodule.person1["age"].
Example
person1 dictionary from the module named mymodule using the from keyword.
Print the "age" value from person1.
Output: complete Python program
from mymodule import person1
print(person1["age"])
Example
mymodule holds one function and one dictionary:def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}