Function objects and __dict__

In the Python docs, it states one attribute of a user defined function object is: ` __dict__`

It's my understanding that this attribute represents the namespace an object.

If I have:

```````

def stuff():

a = 'alpha'

b = 'beta'

print(stuff.__dict__) # retuns {}

`

Why is an empty dictionary returned? I'd have thought that those variables would've been included in the function's dictionary due to that they are being assigned within that namespace.

1 comments · 90% upvoted · other discussions

comments

A_History_of_Silence

Yeah the documentation on that topic is not worded incredibly clearly. Compare the output of the following code to see if it makes more sense:

def f():
    a_local_variable = "test local variable"
    f.an_object_attribute = "test attribute"
    print(locals())
    print(f.__dict__)

Output:

{'a_local_variable': 'test local variable'}
{'an_object_attribute': 'test attribute'}

That said, I don't think I've ever seen someone actually use the __dict__ attribute of a function in real code. Giving a function random attributes is just not usually done.