importing out of cwd
Alex Martelli
aleaxit at yahoo.com
Sun Sep 10 06:09:17 EDT 2000
"Fredrik Lundh" <effbot at telia.com> wrote in message
news:aFHu5.56$F5.8066 at newsb.telia.net...
> Alex Martelli wrote:
> > You do have to temporarily add to sys.path the directory you want,
> > before importing; then, you can take it off again. This should work:
> >
> > import sys
> > sys.path = [".."] + sys.path
> > import whatever
> > sys.path = sys.path[1:]
>
> insert and pop (or del) is slightly more efficient.
Good point. It's also more readable, for sure!
> more importantly, it's a good idea to wrap the import
> inside a try/finally clause, so you don't screw up the
> path if things go wrong:
>
> sys.path.insert(0, "..")
> try:
> import whatever
> finally:
> sys.path.pop(0)
An even better point; it's easy to forget try/finally when
modifying a global data structure with the intent to put it
back afterwards...
Nice to see you back in activity here, btw!-)
Alex
More information about the Python-list
mailing list