Module vs Package
कोई भी Python File एक Module होती है, इसका नाम File के Base Name/Module के __name__ Property बिना .py Extension के होता है।
Package Python Modules का Collection है, यानी एक Package, Python Modules की एक Directory होती है जिसमें एक Additional __init__.py File होती है। __init__.py File एक Package को उस Directory से Distinguish करती है जिसमें बस Python Scripts का गुच्छा होता है। Packages को किसी भी Depth तक Nest किया जा सकता है, बशर्ते कि Corresponding Directories में अपने स्वयं के __init__.py File हों।
जब आप किसी Module या Package को Import करते हैं, तो Python द्वारा Create किया गया Corresponding Object हमेशा Type Module का होता है। इसका अर्थ है कि Module और Package के बीच का अंतर केवल File System Level पर है। हालांकि, ध्यान दें कि जब आप किसी Package को Import करते हैं, तो केवल उस Package की __init__.py File में मौजूद Variables/Functions/Classes Directly Visible होते हैं, Sub-packages या Modules नहीं।
उदाहरण
datetime Module में date नामक एक Submodule होता है। जब आप datetime Import करते हैं, तो यह Import नहीं होगा। आपको इसे अलग से Import करना होगा।
>>> import datetime >>> date.today() Traceback (most recent call last): File "", line 1, in NameError: name 'date' is not defined >>> from datetime import date >>> date.today() datetime.date(2017, 9, 1)
File System Structure:
# Module (Single File)
mymodule.py
# Package (Directory with __init__.py)
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
submodule.py
Key Differences:
| Aspect | Module | Package |
|---|---|---|
| Structure | Single .py File | Directory with __init__.py |
| Contains | Functions, Classes, Variables | Modules, Subpackages |
| Import Result | Module Object | Module Object (Package का) |
| Namespace | Module का Global Scope | Package का __init__.py Scope |