-6

Is it possible in python3 to declare a function inside a nested function? how many levels can I get in ?how to call the display() function?

def calculator():

    def add():

        def display():
Al Xayeed
  • 1
  • 1
  • 1
  • 9
    Yes, just try it – Olivier Melançon Jul 30 '19 at 14:32
  • 4
    The limit should be ~20 https://stackoverflow.com/questions/44972719/why-does-python-have-a-limit-on-the-number-of-static-blocks-that-can-be-nested – Chris_Rands Jul 30 '19 at 14:32
  • 1
    *how to call the display() function?* - you can only call the function in the scope that contains it, which in this case will be only inside the `add()` function – Tomerikoo Jul 30 '19 at 14:34
  • https://stackoverflow.com/questions/1589058/nested-function-in-python might be helpful for some context. – Nickolay Jul 30 '19 at 14:41
  • @OlivierMelançon I have tried it actually.The code doesn't occur any error.But the problem is, the calling the display() function doesn't show any output either – Al Xayeed Jul 30 '19 at 14:43
  • @Chris_Rands Thanks,but I think that is a pretty advance situation than my scenario :( – Al Xayeed Jul 30 '19 at 14:49
  • @Tomerikoo yes,checked.I have tried calling it inside the add(),even inside the display() function itself.It just doesn't produce any error or output – Al Xayeed Jul 30 '19 at 14:51
  • well, that will depend on what it does, which we don't know :) – Tomerikoo Jul 30 '19 at 14:52
  • @Nickolay thanks,there the question is relevant to my code,but I am afraid the objective is not – Al Xayeed Jul 30 '19 at 14:53
  • 1
    @Chris_Rands I was gonna link it! Ah, the memories... – Right leg Jul 30 '19 at 14:55
  • @Tomerikoo actually I have created a scenario like this from my curiosity while learning about nested function.The calculator() function takes two arguments,add() function adds them,the display function will just display it – Al Xayeed Jul 30 '19 at 14:57
  • 1
    yes OK. but if you are not getting any output, I would guess that it is either because you are not calling the functions good, or simply not creating any output (you need to `print` something to see an output). Either way, we can't know because we can't see your code – Tomerikoo Jul 30 '19 at 14:58

1 Answers1

1

Yes, it's certainly possible. As others have said, you'll be limited to 20 levels.

Be careful, though, because a nested function can only be called from the scope it's defined in.

It's also possible to get easily confused with nesting that deep (you may not actually be invoking the inner function like you expect). You can see a working example at:

https://repl.it/repls/AromaticAlphanumericToolbox

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536