user2309351
user2309351

Reputation: 47

Python and function within function recursion

Say I have something like this sample code.

def foo(n):
   def bar():
      return -1
   if n = 0:
      return 0
   else:
      return foo(n+bar())

I assume it creates a new instance of bar every time foo is recursively called. However this seems like something that could be optimized in python (or any other language) but I was unable to find anything stating if it has been optimized for that.

The reasoning I have bar defined in foo is I'm trying to hide bar from the user and python's _bar() or __bar() of "please sir don't use this dear user" is annoying me as I was trained in non scripting languages.

Upvotes: 0

Views: 68

Answers (1)

Tim Peters
Tim Peters

Reputation: 70735

def is an executable statement in Python (and so is class). A new function object for bar is created each time foo() is invoked, but it's pretty trivial cost. It just retrieves the compiled code object, and wraps it in a new function object. People stress over this waaaay too much ;-) In general, it's necessary to do this in order for closures to work right, and to capture appropriate default arguments. You're right that in many cases this could be optimized a bit, but the CPython implementation doesn't bother.

Upvotes: 2

Related Questions