Python Modules

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")

Run Instance

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)

Run Instance

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)

Run Instance

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)

Run Instance

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)

Run Instance

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"])

Run Instance

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"].