package import dangers
Diez B. Roggisch
deets at nospam.web.de
Tue Oct 6 12:42:16 EDT 2009
Ethan Furman wrote:
> Greetings!
>
> I'm working on a package with multiple modules (and possibly packages),
> and I would like to do it correctly. :)
>
> I have read of references to possible issues regarding a module being
> imported (and run) more than once, but I haven't been able to find
> actual examples of such failing code.
>
> My google search was fruitless (although still educational !-), so if
> anyone could point me in the right direction I would greatly appreciate
> it.
The most common problem is that a file is used as module and as executable
at the same time.
Like this:
--- test.py ---
class Foo(object):
pass
if __name__ == "__main__":
import test
assert Foo is test.Foo
---
This will fail when executed from the commandline because the module is
known twice - once as "__main__", once as "test".
So keep your startup-scripts trivial, or don't ever import from them.
You might create similar situations when modifying sys.path to reach *into*
a package - but that would be sick to do anyway.
Other than that, I'm not aware of any issues.
Diez
More information about the Python-list
mailing list