Python中locals()函数为何输出全局变量?末尾locals含全局y的疑问
locals() and globals() in Your Class Definition Let's start by looking at your code again, formatted for clarity:
y=3 class A: x = 1 print(locals()) print() print(globals()) print() print(locals())
Now let's break down your two questions one by one, like we're chatting through a tricky Python quirk.
1. Why does locals() seem to output global variables?
First, let's clear up a common misconception: in the top-level of a class definition, locals() does NOT return the global namespace—it returns a temporary dictionary Python uses to build the class's attributes.
You might be confused because this temporary dict includes auto-generated entries like __module__ (which holds the name of the module where the class lives, e.g., __main__). These are special attributes Python adds automatically, not the global variables you defined (like y=3).
To get straight on the core difference between the two functions:
globals()always returns the module-level global namespace, which includes all your global variables, built-in functions, and module-level attributes.locals()is context-dependent:- At the module level (outside any class/function),
locals()is identical toglobals(). - Inside a function, it returns the function's local namespace.
- Inside a class definition's top-level code, it returns the temporary namespace that will become the class's
__dict__(the dictionary storing class attributes likex).
- At the module level (outside any class/function),
So if you’re seeing entries that look "global" in locals(), they’re likely those auto-added special attributes, not your user-defined global variables.
2. Why does the last locals() include the global variable y?
Wait a second—under normal circumstances, it shouldn’t! When you run your code as-is, the final locals() call should return the same temporary class namespace as the first one: {'__module__': '__main__', '__qualname__': 'A', 'x': 1}.
If you are seeing y in that final locals() output, here are a few possible reasons:
- You might have accidentally assigned
ysomewhere in the class body (even something as simple asy = ywould addyto the class’s temporary namespace). - If you’re running this in an interactive Python shell, there could be leftover state from previous commands messing with the namespace. Try running the code as a standalone script instead to avoid this.
- It’s possible you mixed up the
globals()andlocals()outputs—globals()does includey, so double-check which block you’re looking at.
Double-check your code and the actual output—unless you explicitly add y to the class’s namespace, locals() in the class definition won’t include it.
内容的提问来源于stack exchange,提问作者fardV

