Modules and Packages
-
In the last series we had looked into modules & Packages
-
We can also create sub packages.
-
Then we can access the package and modules inside the packages using relative imports.
- Look at this
from .database import Database
, the period(.) in front of database says use database module inside the current package - Look at his statement
from ..database import Database
we have two periods, navigate one level up (one folder/subpackage) an there we have a module called as database from that import class Database
- Look at this
-
Now consider this statement
from utilities.database.nosql.cassandra import Cassandra
. Here are moving into sub packages.
Organize Content within module
- Inside any module, we can specify variables, classes, and/or functions
- We create some modules as libraries and some as executables.
- Refer the code from here
- main.py is the module which we will be executing
- This main.py uses number.py which acts as library.
- In some cases we might have the same module where we define methods/classes and executing the same module
- In this cases we need to organize the code in the module.
- If we don’t organize code our code might end up some thing like this
class Prime:
def __init__(self, number):
self.number = number
def is_prime(self):
pass
value = 11
prime = Prime(value)
if prime.is_prime():
print("Prime number")
else:
print("Not a prime")
- Every module has a special variable
__name__
that specifies the name of the module when it was imported. But when the module is executed directlypython prime.py
, since there is no import that is happening__name__
variable will have a value__main__
- Using this logic prime.py can be changed to
class Prime:
def __init__(self, number):
self.number = number
def is_prime(self):
pass
def main():
value = 11
prime = Prime(value)
if prime.is_prime():
print("Prime number")
else:
print("Not a prime")
if __name__ == "__main__":
# This module is executed directly
main()
-
Refer test_prime.py file from here
-
Next Steps:
- Access Control in Classes
- Third Party Libraries