Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do python functions have a __dict__?

Tags:

python

In Python, functions created using def and lambda have a __dict__ attribute so you can dynamically add attributes to them. Having a __dict__ for every function has a memory cost. An empty dict uses 140 bytes in CPython 2.6.

Adding attributes to a function isn't a particularly common thing to do, and you can use a custom object with a __call__ method for the cases where you do need a function with non-standard attributes.

Since adding custom attributes to a function isn't a common use case and having a __dict__ has a memory cost why do Python functions have a __dict__?

like image 506
Peter Graham Avatar asked Sep 16 '11 00:09

Peter Graham


3 Answers

PEP 232 has an extensive discussion about this, you might wanna take a look.

like image 172
nye17 Avatar answered Sep 20 '22 08:09

nye17


In Python, functions created using def and lambda have a __dict__ attribute so you can dynamically add attributes to them.

Well, yes; they're objects, after all.

Having a __dict__ for every function has a memory cost. An empty dict uses 140 bytes in CPython 2.6.

It's 124 bytes for me. Not that it really matters for the sake of discussion.

If you really needed to save every byte, you wouldn't be using Python. In a program that uses a lot of memory, functions normally represent a tiny fraction of the number of objects, so the overhead is not really important. IMO you should be much more worried about the fact that it's costing you 16 bytes per floating-point value and you can't switch from double to float. Of course, the way to worry about this is to use Numpy. :)

Adding attributes to a function isn't a particularly common thing to do,

If you come from the Java/C++/C# world, then I imagine it must seem horribly messy to you. But for people who come from the Perl/Javascript world (or even, in a rather different direction, maybe something like Scheme or Haskell), it's pretty elegant.

So basically, I would say the answer is "why not?" :)

like image 25
Karl Knechtel Avatar answered Sep 17 '22 08:09

Karl Knechtel


the empty dict doesn't exist if you don't require it, here is the code to check it:

import gc
f = lambda :1
print {} in gc.get_referents(f)
f.__dict__
print {} in gc.get_referents(f)
like image 30
HYRY Avatar answered Sep 21 '22 08:09

HYRY