[Python-Dev] avoiding accidental shadowing of top-level libraries by the main module

Michael Foord fuzzyman at voidspace.org.uk
Tue Jul 13 00:27:48 CEST 2010


On 12/07/2010 22:59, Antoine Pitrou wrote:
> On Mon, 12 Jul 2010 17:47:31 -0400
> Fred Drake<fdrake at acm.org>  wrote:
>
>    
>> On Mon, Jul 12, 2010 at 5:42 PM, Michael Foord
>> <fuzzyman at voidspace.org.uk>  wrote:
>>      
>>> I'm sure Brett will love this idea, but if it was impossible to reimport the
>>> script being executed as __main__ with a different name it would solve these
>>> problems.
>>>        
>> Indeed!  And I'd be quite content with such a solution, since I
>> consider scripts and modules to be distinct.
>>      
> Except that modules can often be executed as scripts...
>    

Allowing a module-executed-as-script to be in sys.modules twice with 
different names and classes is still a recipe for problems. For example 
see this blog entry from Phil Hassey, an experienced Python developer, 
caused by this issue:

http://www.philhassey.com/blog/2009/07/16/oddball-python-252-import-issue/

For scripts that need to be in sys.modules with their "real" name (e.g. 
modules executed with python -m) the following trivial workaround is 
possible:

if __name__ == '__main__':
sys.modules[real_name] = sys.modules['__main__']

That avoids the problem of error messages like:

TypeError: unbound method foo() must be called with A instance as first 
argument (got A instance instead)

(Two different classes with the same name created - one from __main__ 
and one from real_name.) Use cases for *genuinely* reimporting the same 
module with different names (as different module objects rather than 
aliases) are relatively rare, and the problem of modules *accidentally* 
reimporting themselves not that rare.

All the best,

Michael




> Antoine.
>
>
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/fuzzyman%40voidspace.org.uk
>    


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog

READ CAREFULLY. By accepting and reading this email you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies (”BOGUS AGREEMENTS”) that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer.




More information about the Python-Dev mailing list