Python Modules
- Previous Page Python Scope
- Next Page Python Date
What is a module?
Think of modules similar to code libraries.
A module is a file containing a set of functions, intended to be referenced in an application.
Create a module
To create a module, simply save the required code in a file with an extension of .py
in the file
Instance
named mymodule.py
Code is saved in the file
def greeting(name): print("Hello, " + name)
to use the module
Now, we can use import
statement to use the module we just created:
Instance
Import the module named mymodule
of the module, and call greeting
Functions:
import mymodule mymodule.greeting("Bill")
Note:When using functions from a module, please use the following syntax:
module_name.function_name
Variables in the module
A module can contain functions described previously, but can also contain various types of variables (arrays, dictionaries, objects, etc.):
Instance
in the file mymodule.py
Code is saved in
person1 = { "name": "Bill", "age": 63, "country": "USA" }
Instance
Import the module named mymodule
to access the person1 dictionary of the module:
import mymodule a = mymodule.person1["age"] print(a)
Name the module
You can name the module file freely, but the file extension must be .py
.
Rename module
You can use it to rename a module when importing. as
Keyword to create an alias:
Instance
Create an alias mx for mymodule:
import mymodule as mx a = mx.person1["age"] print(a)
Built-in modules
There are several built-in modules in Python that you can import at any time.
Instance
Import and Use platform
Module:
import platform x = platform.system() print(x)
Use the dir() function
There is a built-in function that can list all function names (or variable names) in a module.dir()
Functions:
Instance
List all defined names belonging to the platform module:
import platform x = dir(platform) print(x)
Note:The dir() function can be used for all modules, as well as for modules you create yourself.
Import from module
You can use the from keyword to import only parts from a module.
Instance
The module named mymodule has a function and a dictionary:
def greeting(name): print("Hello, " + name) person1 = { "name": "Bill", "age": 63, "country": "USA" }
Instance
Import person1 dictionary from module only:
from mymodule import person1 print(person1["age"])
Tip:When using the from keyword to import, do not use the module name when referencing elements within the module. Example: person1["age"], not mymodule.person1["age"].
- Previous Page Python Scope
- Next Page Python Date