A Function's name during its definition

Mark Bourne nntp.mbourne at spamgourmet.com
Tue Feb 7 15:38:00 EST 2023


Stefan Ram wrote:
>    When one defines a function, sometimes its name is only
>    half-existent.
> 
>    One can implicitly evaluate the name of the function:
> 
>    main.py
> 
> def g():
>      def f():
>         print( f )
>      f()
> g()
> 
>    output
> 
> <function g.<locals>.f at ...
> 
>    , but one gets an error when one tries to evaluate it explicitly:
> 
>    main.py
> 
> def g():
>      def f():
>         print( eval( 'f' ))
>      f()
> g()
> 
>    error output
> 
> NameError: name 'f' is not defined

I'm guessing that's because the name "f", referencing that function, is 
in the local scope of the "g" function.

In the first version, the interpreter searches the scope of the code 
which calls "print(f)".  It doesn't find anything named "f" there, so 
searches the next scope out, that of the function identified by "g". 
That contains "f", so it's found and can be printed.

In the second case, eval() only gets the globals and immediate locals, 
in this case the locals of "f".  The name "f" doesn't exist in the local 
scope of "f", and it doesn't exist in the global scope.  So the code 
executed by eval() can't see it.

The following does work:

def g():
     def f():
        print(eval('g'))
     f()
g()

...because in this case "g" is defined in the global scope, so the code 
in the eval call can see it.

The following also works:

def g():
     def f():
         pass
     print(eval('f'))
g()

...because in this case, eval() is called from within the scope of "g", 
so it can see the function "f" defined in that scope.


-- 
Mark.


More information about the Python-list mailing list