Bird
Raised Fist0

You want to add '/temp/modules' to Python's module search path only during the execution of a script without permanently modifying sys.path. Which method is best?

hard🚀 Application Q8 of Q15
Python - Modules and Code Organization
You want to add '/temp/modules' to Python's module search path only during the execution of a script without permanently modifying sys.path. Which method is best?
ASet the PYTHONPATH environment variable before running the script
BInsert the path at the start of sys.path at runtime and remove it after imports
CPermanently append the path to sys.path in sitecustomize.py
DModify sys.modules to include the new path
Step-by-Step Solution
Solution:
  1. Step 1: Understand temporary path addition

    Inserting the directory at the start of sys.path during runtime affects only the current script.
  2. Step 2: Avoid permanent changes

    Removing the path after imports or letting the script end ensures no permanent modification.
  3. Step 3: Evaluate other options

    Setting PYTHONPATH affects environment globally; sitecustomize.py is permanent; sys.modules is unrelated to path.
  4. Final Answer:

    Insert the path at the start of sys.path at runtime and remove it after imports -> Option B
  5. Quick Check:

    Modify sys.path at runtime for temporary effect [OK]
Quick Trick: Modify sys.path at runtime for temporary path [OK]
Common Mistakes:
MISTAKES
  • Using PYTHONPATH which affects environment permanently
  • Editing sitecustomize.py for temporary needs
  • Trying to modify sys.modules for path changes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes