package import dangers

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Oct 6 18:56:06 EDT 2009


On Tue, 06 Oct 2009 18:42:16 +0200, Diez B. Roggisch wrote:

> 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".


Why would a module need to import itself? Surely that's a very rare 
occurrence -- I think I've used it twice, in 12 years or so. I don't see 
why you need to disparage the idea of combining modules and scripts in 
the one file because of one subtle gotcha.




-- 
Steven



More information about the Python-list mailing list