break in a module

Ethan Furman ethan at stoneleaf.us
Thu Jun 16 22:11:29 EDT 2011


Erik Max Francis wrote:
> Chris Angelico wrote:
>> On Fri, Jun 17, 2011 at 10:48 AM, Steven D'Aprano
>> <steve+comp.lang.python at pearwood.info> wrote:
>>> Perhaps the most sensible alternative is conditional importing:
>>>
>>> # === module extras.py ===
>>>
>>> def ham(): pass
>>> def cheese(): pass
>>> def salad(): pass
>>>
>>>
>>> # === module other.py ===
>>>
>>> def spam(): pass
>>>
>>> if not some_condition: from extras import *
>>>
>>
>> This would, if I understand imports correctly, have ham() operate in
>> one namespace and spam() in another. Depending on what's being done,
>> that could be quite harmless, or it could be annoying (no sharing
>> module-level constants, etc).
> 
> No, he's using `from ... import *`.  It dumps it all in the same 
> namespace 

Wrong, with a little bit right.  The 'from ... *' functions are now 
bound in the calling namespace, but they still execute in their original 
namespace.  Observe:

8<--these.py---------------------------------------------------------
import this

this.yummy()

8<--this.py----------------------------------------------------------
breakfast = 'ham and eggs'

def spam():
     print(breakfast)

if 'spam' not in breakfast:
     from that import *

8<--that.py----------------------------------------------------------
def yummy():
     print(breakfast)

8<--results----------------------------------------------------------
--> import these
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "these.py", line 3, in <module>
     this.yummy()
   File "that.py", line 2, in yummy
     print(breakfast)
NameError: global name 'breakfast' is not defined

8<-------------------------------------------------------------------

~Ethan~



More information about the Python-list mailing list