Python Modules

Python Modules

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.


Creating and Using a Module

To create a module, just save the code you want in a file with the file extension .py. To use a module, we use the import statement.

Imagine you have a file named mymodule.py:

def greeting(name):
  print("Hello, " + name)

You can import and use it in another file like this:

import mymodule
mymodule.greeting("Jonathan")

Variables in Modules

The module can contain functions, but also variables of all types (arrays, dictionaries, objects etc).

import mymodule

a = mymodule.person1["age"] print(a)


Built-in Modules

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

Importing Built-in Modules

import platform

x = platform.system() print(x)

The dir() Function

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

Re-naming a Module

You can create an alias when you import a module, by using the as keyword. import mymodule as mx


Exercise

?

Which keyword is used to include a module in your Python code?