Repository navigation
inspect.getclosurevars returns incorrect variable when using class member with the same name as other variable #70764
Description
Activity
If a variable 'x' exists in the global or local scope, and a function (also defined in the same scope as 'x', or lower) refers only to a member named 'x' of an object, inspect.getclosurevars will include a reference to the variable, rather than the member.
Okay, that's kind of confusing to describe, so here's a small example in code form:
import inspect class Foo: x = int() x = 1 f = Foo() assert(f.x != x) func = lambda: f.x == 0 assert(func()) cv = inspect.getclosurevars(func) assert(cv.globals['f'] == f) assert(cv.globals.get('x') != x) # <--- Assertion fails
It is expected that 'x' would not exist in cv.globals, since func does not refer to it. Also, there should be a 'f.x' included somewhere in the ClosureVariables object returned.
- addedstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
on Mar 17, 2016 - addedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Mar 17, 2016 Reproduced on 3.11.
Why is expected that 'x' would not exist in cv.globals? I think it works normally, you can see
xinfunc.__globals__.If you change the class member 'x' to a different name like 'y', then cv
doesn't include 'x', but does include an unbound 'y'.In both cases, the function isn't referring to a global variable, just the
class member of that name. Besides the function itself, no other globals
are included in cv.globals.On Sat, Dec 18, 2021 at 10:34 AM hongweipeng <report@bugs.python.org> wrote:
hongweipeng hongweichen8888@sina.com added the comment:
Why is expected that 'x' would not exist in cv.globals? I think it works
normally, you can seexinfunc.__globals__.----------
nosy: +hongweipeng
Python tracker <report@bugs.python.org>
<https://bugs.python.org/issue26577\>
This had me scratching my head when a class member happened to be named the same as an imported module. Example:
import inspect class TestClass: def __init__(self): self.inspect = 123 self.something = 456 testclass = TestClass() print(inspect.getclosurevars(testclass.__init__))
Output:
ClosureVars(nonlocals={}, globals={'inspect': <module 'inspect' from '/.../python3.11/inspect.py'>}, builtins={}, unbound={'something'})Clearly,
self.inspectrefers to a class member and not the global module, butgetclosurevars()doesn't understand this.It seems pretty easy for this to happen; in my case, it was a setter for
self.imagebeing conflated with an imported moduleimage.- added a commit that references this issue
on Nov 5, 2024 - added a commit that references this issue
on Dec 8, 2024
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsDone
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
Linked PRs