Tuesday, April 22, 2008

Python globals and python packages

Jared's been messing with packages. A lot. "Classes are bound to their globals( ) at definition; packages have their own globals; and there's no way around it." I sure hadn't figured that one out. But I think he's gonna want a different behavior in skaffold. Here's his minimal example of the behavior:

classdef.py:

classdef = """
class C:
def __init__(self):
print where
"""

where = "Package"
exec classdef

>>> import classdef

>>> classdef.where
'Package'
>>> where = "World"
>>> g = { 'where': "Microcosm" }


>>> exec classdef.classdef
>>> exec classdef.classdef in g

>>> c = classdef.C()
Package
>>> c = C()
World
>>> c = g['C']()
Microcosm

>>> from classdef import C; c = C()
Package
>>> exec "from classdef import C; c = C()" in g
Package

Anyone figure out a way to make packages use "the real" globals( )?

No comments: