Python Module

Python module is a file that contains Python code. Python module’s name is the file name without extension. Normally Python module is used to group related functions, classes and variables for better code management and avoiding name clash.  For example in the built-in module, you have a function called f1() and in your program your also want to have function f1 as well. In this case, your need to use module to organize the code so that the function has its own namespace.

Writing the first Python module

We are going the write the first module in Python called mymath. In the module mymath, we define a function called circle_area to calculate circle’s area. Here is mymath.py looks like:

The mymath module is fairly simple. We defined a variable for PI constant and a function to calculate circle’s area.

Python import statement

In order to use Python modules in program, you need to use he import statement. There are three different forms of import statement as follows:

In this form, Python will search for module name with modulename specified followed import keyword and make it available in the calling program.  If the modulename is not found, an error is issued.

The second form of import module explicitly specifies the name that will be imported to the program as below:

In this form, the modules name1, name2, name3 and etc are imported to the calling program.

The third form of import statement as follows:

In this form, the symbol (*) means all public names in the module modulename will be exported to the calling program. Public names are all the names which are not start with underscore (_). If you import two or more modules which have the same name, the name of the last module will replace the name of preceding module in the list.

Using module in the program

Let’s start using the mymath module we’ve created in our program. In the first example we will use the first form of the import statement. Here is the main program:

In this form, to call function we have to use module name as prefix with the dot operator as above example.

If you want to omit the module when you call the function in the calling program, you need to use the second form of import statement.

Private names in Python modules

All the names starting with an underscore will not be exposed to the outside of the module. Those functions, classes and variables are used inside the module only. If you have functions that you don’t want other programs use them, you should put their name starting with an underscore (_). By doing this, you are ensure that the third form of the import statement will not bring private names to the calling program.

  • Was this tutorial helpful ?
  • YesNo