简体   繁体   中英

Python: Strange behavior of locals()

I am experiencing a strange behavior of a built-in function locals() in Python. It is hard to explain exactly, but please take a look at a code:

def Main():
  def F(l=locals()):  print 'F', id(l), l
  a= 100
  F()
  print '1', id(locals()), locals()
  F()

In the local function F , I am assigning locals() into l as a default value for enclosure. Since locals() is a dict , its reference is copied to l . So the last three lines should have the same result.

However the result is like this:

F 139885919456064 {}
1 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
F 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}

The three print statements are called at almost the same time, and id of locals() and l are the same, but the first l used in F does not have content.

I cannot understand why this happened. Can anyone explain this phenomenon? Or is this a known/unknown bug?

Many thanks!

If you read the docs for the locals function, you'll see

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

locals() doesn't just return a dict of local variables; it also updates the dict to reflect current local variable values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM