Import modules

The most common way to create a module is to define a file with the .py extension that will contain the code you want to group separately from the rest of the application.

In the following example we will create a module with two simple functions. We will then import and use these functions in another file.

We will create a module with the following content:

def Welcome(name):
    print("Welcome", name)

def Bye(name):
    print("Bye", name)

The module above contains two simple function that will print the supplied name, along with the greeting. If you follow along, make sure to save the module in the same directory that will also contain the top-level file.

There are two ways to import a module:

  • using the import statement – imports the entire module.
  • using the from…import statement – imports only individual module attributes.

Here is how we can import a module using the import statement:

import simple_module

The first line (import simple_module) imports the content of the file The second line calls the function Welcome and passes the string value of “Bob“. Notice how we must precede the attribute name with the name of the module (without the .py extension). The result of the code above is:

Welcome Bob

We can also use the from…import statement to import only the attribute we need. Here is how it can be done:

from simple_module import Bye

When we import attributes using the from…import statement, we don’t need to precede the attribute name with the name of the module:

>>> from simple_module import Bye
>>> Bye("John")
Bye John

However, if we try to call the Welcome function, we will get an error, because only the Bye function was imported:

>>> Welcome("John")
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
NameError: name 'Welcome' is not defined
Geek University 2022