0

Is there a way I could access a function that is nested inside another function. For example, I have this block of code right here. For example, I did f().s() but it did not work:

def f():   
 def s():   
     print(13)    



                  
Julien
  • 13,986
  • 5
  • 29
  • 53
toina
  • 1
  • 1
  • `f().s()` means the result of `f()` is an object on which you are calling `s()` Which doesn't seems so in your case – Shivam Jha Sep 28 '20 at 05:14
  • Short answer: no. You can do something similar with classes though. – Julien Sep 28 '20 at 05:15
  • 3
    What do you want to achieve here? – theNishant Sep 28 '20 at 05:15
  • 1
    if you want nested function to be called in outer scope better define it outside – Sociopath Sep 28 '20 at 05:17
  • The code object is at `f.__code__.co_consts[1]` but turning that into a callable function has a few hoops to jump through. How this is done in unit tests is at https://stackoverflow.com/questions/40505380/how-to-call-code-objects-in-python – tdelaney Sep 28 '20 at 05:27

3 Answers3

1

Yes, you can:

def f():
    def s():
        print(13)
    return s

Then you can call:

>>> f()()
13

Or if you want to have f().s():

def f():
   class S:
        def s():
            print(13)
    return S
Denis Eliseev
  • 491
  • 4
  • 8
0

You need to specify that the second function is a global var, then you'd need to call the first function in order for Python interpreter to create that second function.

See below;

>>> def foo():
...     global bar
...     def bar():
...             print("Hello world!")
... 
>>> bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> foo()
>>> bar()
Hello world!
>>> 
malisit
  • 1,253
  • 2
  • 17
  • 36
0

you certainly could do something

def f():
   def s():
      print("S")
   return s

f()()

you could also expose them in an internal dict

def f(cmd):
    return {"s": lambda: do_something_s,"y": lambda: do_something_y}.get(cmd,lambda:invalid_cmd)()

then use f("s") or f("y")

none of these are likely to be the correct solution to what you are actually trying to achieve ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179