Docorator Disected

El Pitonero pitonero at gmail.com
Sat Apr 2 23:02:47 EST 2005


Ron_Adam wrote:
>
> So I didn't know I could do this:
>
> def foo(a1):
>     def fee(a2):
>         return a1+a2
>     return fee
>
> fum = foo(2)(6)   <------ !!!

Ah, so you did not know functions are objects just like numbers,
strings or dictionaries. I think you may have been influenced by other
languages where there is a concept of static declaration of functions.

The last line can be better visualized as:

fum = (foo(2)) (6)

where foo(2) is a callable.

-----------

Since a function is an object, they can be assigned (rebound) to other
names, pass as parameters to other functions, returned as a value
inside another function, etc. E.g.:

def g(x):
    return x+3

h = g # <-- have you done this before? assignment of function

print h(1) # prints 4

def f(p):
    return p # <-- function as return value

p = f(h) # <-- passing a function object

print p(5) # prints 8

Python's use of "def" keyword instead of the "=" assignment operator
makes it less clear that functions are indeed objects. As I said
before, this is something to think about for Python 3K (the future
version of Python.)

------------

Function modifiers exist in other languages. Java particularly is
loaded with them.

public static synchronized double random() {
...
}

So your new syntax:

@decorator(a1)(foo)
def foo(): 
   pass 

is a bit out of the line with other languages.




More information about the Python-list mailing list