Functions

Alex Martelli aleaxit at yahoo.com
Mon Aug 18 09:44:53 EDT 2003


Thor wrote:

> In this hypothetical case:
> 
> def f1:

I assume you mean def f1(): here and in similar cases (the
parentheses are syntactically mandatory).

>         f3:

I assume you mean f3() here and in similar cases (the colon
would be a syntax error, the parentheses indicate a call is
being performed).

> def f2:
>         def f3:
>                 pass
>         f1:
> def f4:
>         def f3:
>                 pass
>         f1:
> 
> would the function f1 execute the right f3 depending on from which
> functions is it called?

No.  There is no "dynamic scoping" of names (and the rules are
exactly the same whether you're thinking of names of functions
or names of any other type of object).  f1 would look up name
f3 in its LEXICAL scope, not find it, and therefore produce an
error.  If you added
    global f3
as the first statement of both f2 and f4, right before the
"def f3():" in each of them, then -- as it happens -- you would
get the behavior you're after, in this particular simple case
(both f2 and f4 would, with the 'global', clobber global name
f3 with their own version of function f3 on each execution --
and global names of this module which all functions share ARE
parts of the lexical scope searched for name resolution within
function f1).


Alex





More information about the Python-list mailing list