Functions

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Aug 18 15:01:53 CEST 2003


Thor <thor__00 at yahoo.com> wrote in
news:bhqhm1$1vcq3$1 at ID-108351.news.uni-berlin.de: 

> In this hypothetical case:
> 
> def f1:
>         f3:
> 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?

Why don't you load up the interactive interpreter and try running it? 
You'll find a lot of mistakes in the hypothetical code you entered, 
including the absence of argument lists after the function names, and the 
spurious colons and lack of parenthese on the function calls.

I'll assume you actually meant something like:

def f1():
    f3()
def f2():
    def f3():
        pass
    f1()
def f4():
    def f3():
        pass
    f1()

If the code above is indeed what you intended then calling either f2() or 
f4() will result in a 'NameError' exception because there is no name 'f3' 
in scope from inside f1(). There are local variables 'f3' inside both f2() 
and f4(), but local variables are never visible nor accessible from outside 
the functions in which they are defined. (They are visible from inside 
nested functions, but that is not the situation here.)

To get code something like this to work, you should pass f3 as a parameter 
to f1:

def f1(f3):
    f3()
def f2():
    def f3():
        pass
    f1(f3)
def f4():
    def f3():
        pass
    f1(f3)

Remember, Python functions are just objects like any other and may be 
assigned to variables or passed in and out of other functions.
 
-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list