Modules in Python
Modules in Python
Just like other programming languages C, C++, Java, C#, Ruby which have their own syntax to create modules, Python also has the facility to create modules like the library in C language. While combining the code into one bucket will make the code easy and efficient.
The module is nothing but a file while contains classes, variables, functions, and runnable code.
Example:
def labing( fun ):
print ("namaste : ", fun)
return
You need to save the file as a .py extension and after then you can import the module to a code.
Import statement in python:
Using the import keyword you can call the module to the program and use the functions and other logic to your code.
For example below to import the code.py you need to write the program in this way-
Example1:
# Import module labing using import keyword
import labing
# Here you can call the labing function and use the method listed in that
labing.printlab("Maharaja")
Example2:
#using from .... import ....
from fib import fibonacci
print(fibonaci.save())
Example3:
#including all function from modname module
from modname import *
print(modname.calling())
Locating modules in python:
In a program when you import the module, the Python interpreter finds the respective module in the current namespace as follows.
- Here in the current directory
- Here if the module hasn’t been found then, Python will do searching in each directory in shell variable PYTHONPATH.
- IF not found then, Python will check the module in the default path in the machine.
Dir() function:
dir() is a function which returns the list of string in a sorted manner containing in the modules automatically.
# Here you can import built-in module math
import math
topic = dir(math)
print topic
