એક મોડ્યુલ એક્ર .py ફાઇલ છે; એક પેકેજ મોડ્યુલ્સની ડિરેક્ટરી છે. આયાતો તમને અન્ય મોડ્યુલ્સમાંથી કોડ ઉપયોગ કરવા દે છે, એક પ્રોગ્રામને પુનઃઉપયોગી ભાગોમાં સંગઠિત કરે છે.
મોડ્યુલ્સ અને આયાત
(): a + b
PI =
# main.py — different ways to import
import math_utils # import the whole module
math_utils.add(2, 3) # access via the module name
from math_utils import add, PI # import specific names
add(2, 3) # use directly
from math_utils import add as plus # import with an alias
import numpy as np # common aliasing convention
mypackage/
__init__.py ← marks it as a package (can be empty)
module_a.py
subpackage/
__init__.py
module_b.py
from mypackage.module_a import something
from mypackage.subpackage.module_b import other
__init__.py ફાઇલ એક ડિરેક્ટરીને પેકેજ તરીકે ચિહ્નિત કરે છે (અને પેકેજ-ઇનિટ કોડ ચલાવી શકે છે અથવા from package import * જે પ્રદર્શન કરે તે વ્યાખ્યાયિત કરી શકે છે).
if __name__ == "__main__" મુહાવરોdef main():
print("running as a script")
if __name__ == "__main__": # True only when run directly, not when imported
main()
તે ફાઇલને આયાતી મોડ્યુલ અને ચલાવી શકાય તેવી સ્ક્રિપ્ટ બંને તરીકે કાર્ય કરવા દે છે — તેની હેઠળનો કોડ ફક્ત ત્યારે જ ચલાય છે જ્યારે ફાઇલ સીધી રીતે સંપાદિત થાય (python file.py), જ્યારે આયાત કરવામાં આવે ત્યારે નહીં. લગભગ સાર્વત્રિક Python મુહાવરો.
import sys
sys.path # the list of directories Python searches for imports
# includes: the current directory, installed packages (site-packages), stdlib
import os, json, datetime # standard library — "batteries included"
import requests # third-party — installed via pip from PyPI
મોડ્યુલ્સ અને પેકેજ છે કે કેવી રીતે તમે Python કોડને પુનઃઉપયોગી, જાળવણી યોગ્ય એકમોમાં સંગઠિત કરો છો એક વિશાળ ફાઇલને બદલે — કોઈ પણ બિન-તુચ્છ પ્રોજેક્ટ માટે મૌલિક.
આયાત શૈલીઓ, પેકેજ માળખું (__init__.py), if __name__ == "__main__" મુહાવરો (દ્વિ સ્ક્રિપ્ટ/મોડ્યુલ વર્તન), અને Python કેવી રીતે મોડ્યુલ્સ શોધે છે (sys.path) તે સમજવું પ્રોજેક્ટ્સ માળખો, કોડ પુનઃઉપયોગ, અને વિશાળ માનક લાઇબ્રેરી અને PyPI ઇકોસિસ્ટમ ઉપયોગ કરવા માટે આવશ્યક છે.
આયાત ભૂલો અને માળખું મૂંઝવણ સામાન્ય પ્રારંભિક અવરોધો છે જે આ જ્ઞાન હલ કરે છે.