0

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.

4
  • 1
    The real problem is that you're trying to hide stuff from the user. That's just not the Python way of doing things. If you want to make a function "private", don't include its name in the __all__ global variable of your module. Python doesn't have "real" private functions. If a user wants to access bar, there's no point in slapping them and saying they can't do that.
    – Blender
    Commented Nov 6, 2013 at 4:35
  • 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. If you're using an interpreted language they could just get to your code anyway. Why do you feel the need to hide it so thoroughly. Commented Nov 6, 2013 at 4:36
  • Encapsulation. If a user could go into a private method and modify it without going through the designed for route suddenly the flow of the program is no longer makes sense. EI people like going "oh it's a counter. I want it done twice as fast as I'm not clear why I'm waiting" not realizing it's not simply a counter. Commented Nov 6, 2013 at 4:49
  • @user2309351: Yes, indeed, if a user does mess with your implementation he might (or not) break something. So what ? How is this your problem ? Stupid people will do stupid things anyway, so why bother ? Anyway: Python is not designed to be idiot-proof, so don't waste your time fighting the language, just use it the way it is. Commented Nov 6, 2013 at 8:17

1 Answer 1

2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.