max fraguas
max fraguas

Reputation: 438

Python function's __dict__

I know functions objects have a __dict__. Few times this is used to add attributes to the function. Some people even use it to add anotations to the function.

My doubt is the following. If a have:

def foo():
   a = 2
   return

Where is "a" stored?

I make this question because I was expecting to find it in the __dict__ of foo, but now I know this is not the purpose of a function's __dict__.

If functions are instance objects of the class function, and the namespace of an object is defined by its __dict__. What is the namespace of a?

Upvotes: 2

Views: 645

Answers (1)

Turn
Turn

Reputation: 7020

The variable a doesn't exist when the foo is defined, it is dynamically created when the foo is run, that is why it is not stored as an attribute of the function. Since a exists in the local scope of foo, you can see it with the locals function:

>>> def foo():
...     a = 22
...     print(locals())

>>> foo()
{'a': 22}

Upvotes: 3

Related Questions