4 ms·
IMO, it's generally bad form for a program to be dynamically creating named functions, filling the namespace. That's what inner functions are for. This isn't
by zephjc 17y ago
IMO, it's generally bad form for a program to be dynamically creating named functions, filling the namespace.
That's what inner functions are for. This isn't the best example, but you get the idea:
def foo(mylist):
def n_to_the_n(n):
if n > 1:
return n**n
return 1
return [n_to_the_n(i) for i in mylist]
- pwnstigator 17y agoDo the inner functions get cleaned up after you exit the function body? I'm used to Lisps, where def/defun/define/defn imply internment. For example, in Clojure: (defn foo [list] (defn n-to-nth [n] (Math/pow n n)) (map n-to-nth list)) Would intern the symbol 'n-to-nth in the current namespace. So every time I see "def", I think of something that has that (mild, almost always innocuous) side effect.
- zephjc 17y agoThe inner function just falls out of scope, and is presumably collected. >>> def foo(mylist): ... def n_to_the_n(n): ... if n > 1: ... return n**n ... return 1 ... return [n_to_the_n(i) for i in mylist] ... >>> print foo([1,2,3,4,5]) [1, 4, 27, 256, 3125] >>> foo <function foo at 0x6e5f0> >>> n_to_the_n Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'n_to_the_n' is not defined >>> Note that I only made the inner function longer than necessary for illustrative purposes :-)
- foldr 17y ago>I'm used to Lisps, where def/defun/define/defn imply internment. For example, in Clojure: With regard to 'define', it doesn't work like that in Scheme. A define in a function body behaves just like a let.