Interview question
How does Python find and import modules? What is sys.path? Python modules कैसे ढूंढता और import करता है? sys.path क्या है?
Answer
When you import a module, Python searches through a list of directories stored in sys.path, in order, until it finds a matching module or package.
import sys
print(sys.path)
# Typical output includes:
# ['', '/usr/lib/python3.x', '/usr/lib/python3.x/site-packages', ...]
# Search order (roughly):
# 1. The directory of the script being run (or '' for current directory)
# 2. PYTHONPATH environment variable directories (if set)
# 3. Standard library directories
# 4. site-packages (where pip installs third-party packages)
# Adding a directory to sys.path at runtime (not usually recommended,
# but useful for scripts or debugging)
import sys
sys.path.append('/path/to/my/modules')
import my_custom_module # now findable
# ModuleNotFoundError happens when Python searches ALL of sys.path
# and doesn't find a matching module/package anywhere
# import nonexistent_module # ModuleNotFoundError: No module named 'nonexistent_module'
# Checking where a specific module was loaded from
import json
print(json.__file__) # shows the actual file path used
# Import caching - a module is only executed ONCE per process,
# even if imported multiple times from different files
import sys
print('mymodule' in sys.modules) # True if already imported somewhereImport करते समय, Python sys.path में stored directories की list में क्रम से search करता है जब तक matching module या package न मिल जाए।
import sys
print(sys.path)
# आमतौर पर शामिल: ['', '/usr/lib/python3.x', 'site-packages', ...]
# Search order (लगभग):
# 1. चल रही script की directory
# 2. PYTHONPATH environment variable
# 3. Standard library directories
# 4. site-packages (pip से installed packages)
# Runtime पर sys.path में directory add करना
import sys
sys.path.append('/path/to/my/modules')
import my_custom_module
# ModuleNotFoundError तब आता है जब पूरे sys.path में module नहीं मिलता
# कौन-सी file से module load हुआ check करना
import json
print(json.__file__)
# Import caching - module एक बार ही execute होता है process में
import sys
print('mymodule' in sys.modules)Was this answer clear?