7
class Foo(object):

    def __init__(self, x):
        self.bar(x=x)

    def bar(self, **kwargs):
        print kwargs
        locals().update(kwargs)
        print x


f = Foo(12)

this seems obvious, but it doesn't work, the first print would output {'x': 12}, which is correct, however, then I get this error: NameError: global name 'x' is not defined

Why would this happen? thanks.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
wong2
  • 34,358
  • 48
  • 134
  • 179
  • 12
    Have you checked the [docs on `locals()`](http://docs.python.org/2/library/functions.html#locals): Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter. – Ashwini Chaudhary Feb 17 '14 at 10:48
  • 5
    Python does **not** have any *reliable* way of creating locals at runtime. Even `exec` wont work in many python versions (e.g. python3+ where `eval` is a function). – Bakuriu Feb 17 '14 at 10:53

1 Answers1

3

The dictionary returned by locals() is read-only by contract. You cannot add variables dynamically to the current scope.

salezica
  • 74,081
  • 25
  • 105
  • 166