0

How to call function f2?

def f1():
    print( "f1" )
    def f2():
        print( "f2" )

#f1.f2()

more explain:
by this link http://stackoverflow.com/questions/11154634/call-nested-function-in-python its work with this code:

def f1():
    print( "f1" )
    def f2():
        print( "f2" )
    f1.f2 = f2

f1()
f1.f2()

is there anyway to cal f2 directly. without call f1 first?

mlibre
  • 2,460
  • 3
  • 23
  • 32
  • 1
    possible duplicate of [Call Nested Function in Python](http://stackoverflow.com/questions/11154634/call-nested-function-in-python) – Michael Recachinas Aug 18 '15 at 18:17
  • 1
    No, there is not. Just like you can't specify a file without giving its full path. How would the computer know where to look for it? If you want `f2` in the outer scope, just put it there. – Two-Bit Alchemist Aug 18 '15 at 19:05

3 Answers3

2

It is impossible.

The function f2 is defined within f1. It is not defined until f1 has been called.

In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def f1():
:    print( "f1" )
:    def f2():
:        print( "f2" )
:--

In [2]: f1()
f1

In [3]: f2()
--------------------------------------------------------------------
NameError         Traceback (most recent call last)
<ipython-input-3-fdec4c1c071f> in <module>()
----> 1 f2()

NameError: name 'f2' is not defined

In [4]: f1.f2()
--------------------------------------------------------------------
AttributeError         Traceback (most recent call last)
<ipython-input-4-3af025f48622> in <module>()
----> 1 f1.f2()

AttributeError: 'function' object has no attribute 'f2'

It cannot be called outside of f1, the name f2 is not defined outside the scope of f1.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
2

You can't call f2 until you have executed f1 at least once because until f1 is executed, f2 doesn't exist. It is the action of executing the code of f1 that causes f2 to be created as a function and then become callable.

In Java, class or method definitions are created at compile time, which allows you to access them without having executed the parent container. Not true with Python.

ZeddZull
  • 276
  • 1
  • 4
2

The f2() function is created by the call to f1().

So, no you can't call f2 without f1 because it doesn't exist yet :-)

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485