Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locals().update(kwargs) is not working [duplicate]

Tags:

python

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.

like image 972
wong2 Avatar asked Feb 17 '14 10:02

wong2


1 Answers

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

like image 180
slezica Avatar answered Sep 23 '22 15:09

slezica