Modules in Python 3

Jigisha Sata

a year ago

Modules In Python
Modules In Python

What is module?

Python encompasses a thanks to place definitions associate degree exceedingly in a very} file and use them in an exceedingly script or in an interactive instance of the interpreter.
A module could be a file containing Python definitions and statements. The file name is that the module name with the suffix .py appended.
So, in short, we will tell module permits us to arrange our python code logically. Grouping connected code into a module makes the code easier to grasp and use. A module could be a Python object with willy-nilly named attributes that we will bind and take a reference whenever required.
Simply, a module could be a file consisting of Python code. A module will outline functions, categories and variables. A module can even embrace runnable code.
Example
The Python code for a module named a name normally resides in a file namedaname.py. Let’s take an example of a simple module, hello.py −
def print_func( par ):
   print ("Hello: ", par)
   return 

What is import Statement?

You can import any python source code from a module to use it in a different place. It can be done as follows:
import module1[, module2[,... moduleN]
Let’s see how it’s work
When the interpreter sees an import statement, it will try to import the module if the module is coming in the search path. The search path is nothing but it’s a list of directories that the interpreter searches before importing a module.
Let’s take an example to understand it.
If we want to import the module hello.py, we can put the following command:
#!/usr/bin/python3

# Import module hello
import hello

# Now you can call a defined function that module as follows
hello.print_func("USER")


The output of the above code −
Hello: User
Only once the module gets imported regardless of the number of times it is imported. It helps to prevent multiple imports.

What is the from...import Statement in python?

When we want to import a specific part of the module into current place to use it then we use from…import statement.
We can do it as mentioned below.
from module_name import name1[, name2[, ... nameN]]
For example, to import the function Fibonacci from the module fibo, use the following statement −
#!/usr/bin/python3

# Fibonacci numbers module

def fibo(n): # return Fibonacci series up to n
   result = []
   a, b = 0, 1
   while b < n:
      result.append(b)
      a, b = b, a + b
   return result
>>> from fibo import fibo
>>> fibo(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
This statement doesn't import the complete module fib into the present namespace; it simply introduces the item Fibonacci from the module fibo into the global table of the importing module.

What is from...import * Statement?

Now suppose you want to import all the names from a module. This can be done as mentioned below.
from module_name import *
This provides a straightforward way to import all the things from a module into the present namespace; but, this statement ought to be used slenderly.

Executing Modules as Scripts

Within a module, the module’s name (as a string) is available as the value of the global variable __name__. The code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__".
Add this code at the end of your module –
#!/usr/bin/python3

# Fibonacci numbers module

def fibo(n): # return Fibonacci series up to n
   result = []
   a, b = 0, 1
   while b < n:
      result.append(b)
      a, b = b, a + b
   return result
if __name__ == "__main__":
   f = fibo(100)
   print(f)
When you execute the above code, the following is the output we get.
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Locating Modules

When you import a module, the Python interpreter searches for the module in the following sequences −
  • The current directory.
  • If the module is not found, Python then searches each directory in the shell variable PYTHONPATH.
  • If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python3/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.
This is a typical PYTHONPATH from a Windows system −
set PYTHONPATH = c:\python34\lib;
And this is a typical PYTHONPATH from a UNIX system −
set PYTHONPATH = /usr/local/lib/python

What are Namespaces and Scoping?

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
  • A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.
  • Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
  • Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
  • Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
  • The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.
For example, we define a variable Income in the global namespace. Within the function Income, we assign Income a value, therefore Python assumes Income as a local variable.
However, we accessed the value of the local variable Income before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python3

Income= 2000
def AddIncome():
   # Uncomment the following line to fix the code:
   # global Income
   Income = Income + 1

print (Income)
AddIncome()
print (Income)


What is dir( ) Function?

The dir()  is built-in function which returns a sorted list of strings containing the names defined by a module.
The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

#!/usr/bin/python3

# Import built-in module math
import math

content = dir(math)
print (content)

The above code produces the below result:
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh']


Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.

What are globals() and locals() Functions?

When you want to return the names in global and local namespaces depending upon the loactions there we use globals() and local() functions.
  • If locals() is called from within a function, it will return all the names that can be accessed locally from that function.
  • If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
The return type of both these functions is a dictionary. Therefore, names can be extracted using the keys() function.

The reload() Function

When a module is imported into a script, the code in the top-level portion of a module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −

reload(module_name)
Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −

reload(hello)

Packages in Python

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in the Phone directory. This file has the following line of source code −
#!/usr/bin/python3

def Pots():
print ("I'm Pots Phone")

Similar, we have other two files having different functions with the same name as above. They are 
  • Phone/Isdn.py the file having function Isdn()
  • Phone/G3.py file having a function G3()
Now, create one more file __init__.py in the Phone directory −
  • Phone/__init__.py
To make all of your functions available when you have imported Phone, you need to put explicit import statements in __init__.py as follows −
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available when you import the Phone package.
#!/usr/bin/python3

# Now import your Phone Package.
import Phone

Phone.Pots()
Phone.Isdn()
Phone.G3()


Following are the result produced −
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

In the above example, we've taken an example of one function in every file, however, you'll be able to keep multiple functions in your files. you'll be able to additionally outline completely different Python classes in those files and so you'll be able to produce your packages out of these classes.
I hope you enjoyed reading this article and finally, you came to know about Modules in Python 3.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review

We're Online!

Chat now for any query