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.
The dictionary returned by locals()
is read-only by contract. You cannot add variables dynamically to the current scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With