Function declarations ?

Gregory Ewing greg.ewing at canterbury.ac.nz
Mon Jun 13 22:03:30 EDT 2011


Tim Roberts wrote:
> Andre Majorel <cheney at halliburton.com> wrote:
> 
>>Anyway, it seems the Python way to declare a function is
>>
>> def f ():
>>   pass
> 
> No, that DEFINES a function.

Actually, it's more illuminating to say that it *creates* a function.

The 'def' statement in Python is an executable statement. Executing
it has the effect of creating a function object and binding it to
the indicated name. Before that has happened, attempting to execute
any code referring to that name will fail.

Conversely, the function name doesn't need to be bound until the
code referring to it is actually executed. So...

>     def g():
>         return f()
>     def f():
>         return 3
>     print g()

works because by the time g is *called*, both def statements
have been executed, and both function names have therefore been
bound.

-- 
Greg



More information about the Python-list mailing list