Tuesday, March 21, 2017

When you can update locals()

There are two built-in functions, globals and locals.  These return dicts of the contents of the global and local scope.

Locals usually refers to the contents of a function, in which case it is a one-time copy.  Updates to the dict do not change the local scope:

>>> def local_fail():
...    a = 1
...    locals()['a'] = 2
...    print 'a is', a
... 
>>> local_fail()
a is 1

However, in the body of a class definition, locals points to the __dict__ of the class, which is mutable.

>>> class Success(object):
...    locals().update({'a': 1})
... 
>>> Success.a
1

3 comments:

  1. i like this publish. I apprehend that my goal readers are my students within the past. custom essay writing service I’d like to mark like this too appealing occasion and actual hard paintings to make a first rate article. thanks for the pointers, I without a doubt cherished reading this. it is so plenty inspiring.

    ReplyDelete
  2. Many parents take their children for education trips but there are still some parents that can't come up with a trip plan for their kids. Unfortunately, these parents fail to recognize the importance of educational trips for children and how it can mould a child into a responsible, intelligent adult. 1: Children Get To Know Their Family Better Educational trips with family give children an opportunity to interact better in a social setup, especially if the trip has other family members and friends.http://www.how-todo.xyz/

    ReplyDelete