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__
?
PEP 232 has an extensive discussion about this, you might wanna take a look.
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?" :)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With