dynamic creation of global Identifier
Steve Holden
steve at holdenweb.com
Wed Oct 11 06:19:28 EDT 2006
Theerasak Photha wrote:
> On 10/11/06, Alexander Eisenhuth <newsuser at stacom-software.de> wrote:
>
>
>>but why doesent exec "global ... create a identifier in the global namespace.
>
>
> I haven't had much use for exec, but it operates in its own, more or
> less cloistered namespace. It can't set globals among other things.
>
Well that's not strictly true:
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__':
'__main__', '__file__': '/c/Steve/.pythonrc', 'sys': <module 'sys'
(built-in)>, '__doc__': None}
>>> exec "NEW = 42"
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'/c/Steve/.pythonrc', 'sys': <module 'sys' (built-in)>, 'NEW': 42,
'__name__': '__main__', '__doc__': None}
The problem was that the two exec statements were being treated
separately because they use independent execution contexts. Make them
the same, and bingo!
sholden at bigboy ~/Projects/Python
$ cat test38.py
class A:
def __init__(self, v):
print "ctr of", self.__class__, "with", v
self._v = v
def init():
newIdentifier = ["a", "b"]
param = [1,2]
for newId, par in zip(newIdentifier, param):
exec """\
global %s
%s = A(par)""" % (newId, newId)
init()
print a, b
sholden at bigboy ~/Projects/Python
$ python test38.py
ctr of __main__.A with 1
ctr of __main__.A with 2
<__main__.A instance at 0x186c6d2c> <__main__.A instance at 0x186c6e0c>
However, none of this will necessarily get the OP further, since the
interpretation of the global statement will be as "global to the module
that it appears in".
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list