[Python-Dev] decorators (not transformations) on functions vs classes

Jewett, Jim J jim.jewett at eds.com
Fri Mar 26 13:09:40 EST 2004


>> I would also guess that where people are using function attributes,
>> there's a good chance that they're using decorators as well, since
>> they probably need to *do* something with the attributes.

> Depends entirely on the usage.

An attribute affects how the object looks when viewed as data.
For a function, that is all it does; it does not affect 
semantics.  For a class, it can also affect how the class acts.

If the object is just for storage/persistence, it is probably
a class rather than an function.  (Example: Values class of optparse)

    class foo:
        pass
    foo.x = 27

has some meaning.  Any subclass or instance of foo (including 
those already created) will now have an attribute of x, with 
a default value of 27.  Methods can use this value.  Other
code may (idiomatically) use the value to control its own
settings.

    def bar():
        pass
    bar.x = 27

is not so useful.  

There is no intermediate "self" scope between function locals 
and global, so bar itself can't see x.  Functions do not inherit,
so there won't be any instances or subfunctions that could be
affected.  Using a function's attributes to control another
function's execution path is surprising.

For a function, the attribute is only meaningful when viewing
the object as data rather than code.  Many programmers take
this opportunity to replace the function entirely with a class; 
others use naming conventions.  If these solutions aren't careful 
enough then you may not want to trust an attribute; you should 
run the function on known input and test the output.  (And then 
maybe cache the answer on the function, hoping that no one else
will change it, even if they would not have followed the naming
convention.)

-jJ



More information about the Python-Dev mailing list