Saturday, October 27, 2018

Modules in Python

While programming you might have come across with a situation where there is a function that you want to use in many programs without copying it into each program. For example the greet_emp() we made in previous post. This can be used by various departments who have newly joined employees. Thus such functions should be stored in a in a separate file called a module and then importing that module into your main program.

A module usually contains statements that have some relation with each other, such as a function and its related declarations or unrelated statements, which are written to perform a specific task. Modules can be made to interact with each other to access each other’s attributes.

To be able to use a piece of code stored in a module, a module should be shared. The process of bringing in the attributes, such as variables and functions, of one module into another or at the interpreter itself is called importing. Importing is the basis of a module in Python. It is this feature that allows variables and functions declared in one module to be shared in different modules. An import statement tells Python to make the code in a module available in the currently running program file.

In other words, a module is a Python file containing Python definitions and statements. The filename is the name of the module with the .py extension appended. Here’s an example of a simple module -

def greet_emp(enames):
   
    for name in enames:
       
        greeting = "Welcome aboard " + name + "!"
        print(greeting)


Use any text editor to write the preceding code and save it as greet_emp.py. Storing your functions in a separate file allows you to hide the details of your program’s code and focus on its higher-level logic. It also allows you to reuse functions in many different programs. When you store your functions in separate files, you can share those files with other programmers without having to share your entire program. Knowing how to import functions also allows you to use libraries of functions that other programmers have written.

There are several ways to import a module, let's see each of these briefly.

1. Importing an entire module

Let us use the module greet_emp.py which we have created recently. We'll use this module in a program welcome_emp.py, which will welcome new employees in a department. Here is the code snippet -

import greet_emp
   
users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp.greet_emp(users)


When Python reads this file, the line import greet_emp tells Python to open the file greet_emp.py and copy all the functions from it into this program. You don’t actually see code being copied between files because Python copies the code behind the scenes as the program runs. All you need to know is that any function defined in greet_emp.py will now be available in welcome_emp.py.

To call a function from an imported module, enter the name of the module you imported, greet_emp, followed by the name of the function, greet_emp(), separated by a dot, i.e greet_emp.greet_emp().When we run this program we'll get the following output -





This first approach to importing, in which you simply write import followed by the name of the module, makes every function from the module available in your program. If you use this kind of import statement to import an entire module named mod_name.py, each function in the module is
available through the following syntax - mod_name.func_name()


2. Importing a specific module

It is also possible to import a specific function from a module. Here’s the general syntax for this approach

from mod_name import func_name

Let us add one more function goodbye_emp() in our module greet_emp.py. The code is shown below-

def goodbye_emp(ename):
   
    farewel = "\nGood luck for your future endeavors " + ename + " we will miss you"
    print(farewel)


In order to use this function in our program farewel.py we'll import goodbye_emp() as follows -

from greet_emp import goodbye_emp

goodbye_emp('Veevaeck')


The output of the program is shown below-



It's possible to import as many functions as we require from a module by separating each function’s name with a comma -

from mod_name import func_name1, func_name2, func_name3

Thus to use both greet_emp() and goodbye_emp() in a new program hrgreetings.py we will use the following statement -

from greet_emp import greet_emp,goodbye_emp

The program is shown below -

from greet_emp import greet_emp,goodbye_emp

users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp(users)
goodbye_emp('Veevaeck') 


When we run this program we'll get the following output -



In case you haven't notice, with this syntax, you don’t need to use the dot notation when you call a
function. Because we’ve explicitly imported the functions greet_emp and goodbye_emp in the
import statement, we can call it by name when we use the function.


3. Importing a function using alias

We have used a common name greet_emp for our module as well as function which sometimes be confusing or conflict with an existing name in our program. Also  if the function name is long, you can use a short, unique alias—an alternate name similar to a nickname for the function.

We’ll give the function this special nickname when we import the function. So in our program farewel.py we'll import goodbye_emp() as follows -

from greet_emp import goodbye_emp as ge

ge('Veevaeck')

Here we have given the function goodbye_emp() an alias, ge(), by importing goodbye_emp as ge. The as keyword renames a function using the alias you provide.

Any time we want to call goodbye_emp() we can simply write ge() instead, and Python will run the code in goodbye_emp() while avoiding any confusion with another goodbye_emp() function you might have written in this program file.

The general syntax for providing an alias is: from module_name import function_name as fn

4. Importing a module using alias

We can also provide an alias for a module name. Giving a module a short alias, like g for goodbye_emp , allows you to call the module’s functions more quickly.

Calling g.goodbye_emp() is more concise than calling goodbye_emp.goodbye_emp(). Thus our program welcome_emp.py, can be re-written as follows -

import greet_emp as g
   
users = ["Bob","Ted", "Joey","Chris","Mac"]
g.greet_emp(users)


The module greet_emp is given the alias g in the import statement, but all of the module’s functions retain their original names. Calling the functions by writing g.greet_emp() is not only more concise than writing goodbye_emp.goodbye_emp(), but also redirects your attention from the module name and allows you to focus on the descriptive names of its functions. These function names, which clearly tell you what each function does, are more important to the readability of your code than using the full module name.

The general syntax for this approach is: import mod_name as mn

5. Importing all functions in a module

We can tell Python to import every function in a module by using the asterisk (*) operator .The re-written program hrgreetings.py is shown below -

from greet_emp import *

users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp(users)
goodbye_emp('Veevaeck')


The asterisk in the import statement tells Python to copy every function from the module greet_emp into this program file. Because every function is imported, you can call each function by name without using the dot notation. However, it’s best not to use this approach when you’re working with larger modules that you didn’t write: if the module has a function name that matches an existing name in your project, you can get some unexpected results. Python may see several functions or variables with the same name, and instead of importing all the functions separately, it will overwrite the functions.

The best approach is to import the function or functions you want, or import the entire module and use the dot notation. This leads to clear code that’s easy to read and understand. I include this section so you’ll recognize import statements like the following when you see them in other people’s code:

from mod_name import *

With this our discussion over functions in Python is completed. Make some more programs and use the concepts learned so far. A thorough understanding of modules is a must for Python Programming due to their utility in real world projects.

So keep practicing and learning Python as Python is easy to learn!
Share:

0 comments:

Post a Comment