Invisible function attributes

Alex Martelli aleax at aleax.it
Fri Sep 5 10:48:30 EDT 2003


Olivier Lefevre wrote:
   ...
> function is a class) and, since functions can't have instances, treating
> it as a sort of static member of the function, which should be available
> as soon as declared. Obviously I got it all wrong. Instead, they work

Basically only in the "declared" part.  Python has no declarations, only
executable statements.

> like local variables except that they "persist" after the function has
> exited. That still feels weird to me. What are they used for? Give me
> a compelling reason to have such a beast in the language.

The ability to associate arbitrary information with a function can be 
used by any framework for the framework's own purposes.  Historically,
some frameworks were (ab)using function's docstrings (attribute __doc__)
for such purposes; arbitrary function attributes were added to Python
so that frameworks would use them instead of __doc__, leaving the
latter free for its intended use, i.e., human-readable documentation.

For a small-scale toy example, consider an "accumulator-maker".  One way
you could code it might be:

def makeAccumulator():
    def accumulate(x):
        accumulate.total += x
    accumulate.total = 0
    return accumulate

to be used, e.g., as:

a = makeAccumulator()

for x in (3, 4, 10, 23, 12): a(x)

print a.total

Of course, one could redesign makeAccumulator to return a class
instance rather than a function:

class makeAccumulator(object):
    def __init__(self):
        self.total = 0
    def __call__(self, x): 
        self.total += x

to be used in the same way.  Generally, classes and their
instances are a more general and powerful way than closures &c
to associate data and behavior in Python.  Still, Python does
support closures to some limited extent, and the ability to
associate arbitrary attributes to each function object can be
seen, in part, as a natural complement for that support.


Alex





More information about the Python-list mailing list