Function declarations ?

Asen Bozhilov asen.bozhilov at gmail.com
Fri Jun 10 18:46:17 EDT 2011


Andre Majorel wrote:

> Is there a way to keep the definitions of the high-level
> functions at the top of the source ? I don't see a way to
> declare a function in Python.

I am not a Python developer, but Pythonic way of definition not
declaration is definitely interesting. Languages with variable and
function declarations usually use hoisted environment. JavaScript is
the perfect example. Hoisted environment allows you to use call
expression before the physical declaration of the function in the
source text.

e.g.

foo();

function foo() {}

This code does not throw ReferenceError or TypeError in JavaScript. It
calls `foo' exactly because it is used a hoisted environment. More
precisely on entering in some context global or function JS engine
define all function declarations as local scoped variables. While this
has its advantages, it has a really big drawback. It cannot support
default arguments which are bound to local variables.

x = 10
def f(y = x):
    print y

f() #10

This in hoisted environment cannot be implemented, because assignment
is evaluating during the execution of the code, not on entering in
specific context. So the interpreter is not able to predict the value
for y here.

Hope this helps, why Python use definitions instead of declarations.



More information about the Python-list mailing list