yet another modifying locals() question

Ed Anuff ed.anuff at
Mon Sep 14 03:52:47 CEST 2009

I know that locals() is not supposed to be modifiable under most
circumstances, but I'm trying to solve a situation where I'm
dynamically generating some class attributes and it seemed to be the
best way, so I tried something out that seems to work but I'm not sure
that it's kosher:

>>> def f(l):
...    l['b'] = 1
>>> class A:
...    f(locals())
>>> A.b

In my code, I'm doing something quite a bit more complex than just
assigning a single attribute, but this is the simplest use case

Is there a reason why this works and is it safe to rely on it or is
there a better approach?  BTW, this works in a program too, it's not
just an artifact of the command line interpreter globals() = locals()



More information about the Python-list mailing list