In one of my testing scripts in Python I use this pattern several times:
sys.path.insert(0, "somedir")
mod = __import__(mymod)
sys.path.pop(0)
Is there a more concise way to temporarily modify the search path?
In one of my testing scripts in Python I use this pattern several times:
sys.path.insert(0, "somedir")
mod = __import__(mymod)
sys.path.pop(0)
Is there a more concise way to temporarily modify the search path?
Appending a value to
sys.path
only modifies it temporarily, i.e for that session only.Permanent modifications are done by changing
PYTHONPATH
and the default installation directory.So, if by temporary you meant for current session only then your approach is okay, but you can remove the
pop
part ifsomedir
is not hiding any important modules that is expected to be found in inPYTHONPATH
,current directory or default installation directory.http://docs.python.org/2/tutorial/modules.html#the-module-search-path
You could use a simple context manager:
Then to import a module you can do:
On exit from the body of the
with
statementsys.path
will be restored to the original state. If you only use the module within that block you might also want to delete its reference fromsys.modules
: