Why are object attributes used in a function said to be unbound variables?

Viewed 85

I'm using the inspect module to learn more about function namespaces:

import inspect

def foo():
    inspect.__cache__.update({'dummy': 0}) # Could be any class/attribute here

print(inspect.getclosurevars(foo))

Reformatted output:

ClosureVars(
    nonlocals={}, 
    globals={'inspect': <module 'inspect' from ='C:\\Users\\guido\\AppData\\Local\\Programs\\Python\\Python39\\lib\\inspect.py'>}, 
    builtins={}, 
    unbound={'__cache__', 'update'}
)

Why are attributes of objects used in a function (i.e. __cache__ and update in this particular case) said to be unbound variables?


Upon a closer look, inspect.getclosurevars determines unbound variables from the bytecodes. More specifically, it returns variables in foo.__code__.co_names that is in foo.__globals__.

So the real questions are perhaps:

  • Do object attributes belong in foo.__code__.co_names as per the current definition? This is a difficult question on itself because it seems like the definition is yet to be determined
  • Is it correct for the inspect module to determine unbound variables like it is currently doing? Here correct refers to whether the returns conform to the definition of unbound variables.
0 Answers
Related