2
\$\begingroup\$

I implemented this context manager for importing modules from arbitrary directories.

Good? Bad? - Keen to get thoughts:

Implementation


import sys 

class CustomPath:
    def __init__(self, path:str):
        self.original_path = sys.path
        self.custom_path = path 
        
    def __enter__(self):
        sys.path.insert(0, self.custom_path)
        
    def __exit__(self, type, value, traceback):
        sys.path = self.original_path

Usage

Consider this directory structure:

 - project1
    |- notebooks/
         |- notebook1.ipynb
 - project2
 - ...
 - project5/
    |-somefiles/
          |- common_utils.py

I can run this in the notebook1.ipynb and it works:

with CustomPath('../../project5/somefiles/'):
   from common_utils import connect_to_db
    
\$\endgroup\$
5
  • \$\begingroup\$ Interesting, but have you considered the importlib module? \$\endgroup\$ Commented Nov 30, 2022 at 20:37
  • \$\begingroup\$ I did, but I could not get it to work, probably due to relative imports. \$\endgroup\$ Commented Dec 1, 2022 at 11:04
  • \$\begingroup\$ Do you see any potential problems if this were used in a multithreaded application, specifically with two threads doing doing imports with your context manager? \$\endgroup\$ Commented Jun 29, 2023 at 20:12
  • \$\begingroup\$ Honestly no idea, it never occurred to me to import things inside a thread. \$\endgroup\$ Commented Jun 30, 2023 at 9:33
  • \$\begingroup\$ I don't believe that your code would be thread-safe and that could limit its utility in the future. \$\endgroup\$ Commented Jul 3, 2023 at 20:23

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.