You are on page 1of 2

Variables in Modules

The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

Example: Save this code in the module file mymodule.py


person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example: Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Result: 36

1. Re-naming a Module: You can create an alias when you import a module, by using
the as keyword:

Example: Create an alias for mymodule called mx:


import mymodule as mx
a = mx.person1["age"]
print(a)
Result: 36

2. Built-in Modules: There are several built-in modules in Python, which you can import
whenever you like.

Example: Import and use the platform module:


import platform
x = platform.system()
print(x)
Result: Windows

3. Using the dir() Function: There is a built-in function to list all the function names (or variable
names) in a module. The dir() function:

Example: List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)

The dir() built-in function returns a sorted list of strings containing the names defined by a
module. The list contains the names of all the modules, variables and functions that are defined in
a module. Following is a simple example −
# Import built-in module math
import math
content = dir(math)
print content
When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__ is the filename from
which the module was loaded.
Note: The dir() function can be used on all modules, also the ones you create yourself.

You might also like