Modules and Packages
- A module is a file of any python code. We need not do any thing special, Every python file is considered as module (name with .py)
- Refer Here for the sample usage of the python module
- Now when we write python code in .py files there are two usage
- directly execute the python code
python modulename.py
- importing the python code into other modules
import <module>
- directly execute the python code
- Refer Here for the implementation
__name__
to differentiate module execution vs import - Refer Here for importing module using from
- Importing a module with other name
import options as o
from numbers import factors
hotel = o.pick_a_hotel()
print(f"Lets go to {hotel}")
print(factors(8))
- Imported options module as o and called the pick_a_hotel method
Exercise
-
Create a new directory ‘numerical’ and Create following python modules
- query: In this module create functions
- is_prime
- is_even
- operations: In this module implement the following functions
- factors
- factorial
- monetary: In this module implement the following functions
- simple_interest
- compound_interest
- query: In this module create functions
-
Refer Here for the implementation
Module Search Path
- Python looks under current directory for resolving modules
>>> import sys
>>> for place in sys.path:
... print(place)
- The initial empty string represents the current directory ![Preview]https://directdevops.blog/wp-content/uploads/2021/06/py11.png)
Terms
- Module
- Package