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
  • 221,210
  • 51
  • 432
  • 478
wong2
  • 31,730
  • 45
  • 128
  • 170
  • 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
  • @AshwiniChaudhary thanks! #TIL – wong2 Feb 17 '14 at 11:07

1 Answers1

3

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

slezica
  • 69,920
  • 24
  • 96
  • 160