Richard D. Moores dixit:
> I'm working on a function that seems to cry out for some of its code
> to be put in a function. For convenience sake, I've put this new
> function inside the one that calls it.
>
> Question 1: Is this bad practice? It works fine that way, but..
>
> Question 2: If the answer to Q1 is no, is there a standard place to
> put a function inside of another function? Is it standard to have it
> the first line of the function? I've put mine at the point where it
> would be called, mainly as a reminder to myself.
>
> An outline of the big function is:
>
> if:
> else:
> for loop
> for loop
> if
> elif
> the function
> call the function
> else
>
> Thanks,
Do you realize the inner func will be redefined before each call? Meaning in
your case n calls x n outer loops x n inner loops.
def f() ...
is actually a kind of masked assignment
f = function()...
To avoid polluting the global namespace (if it's what you mean), you can
assiattach the inner func as an attribute of the outer: "g.f = f".
Unfortunately, it's not possible (I guess), to define it directly using "def
g.f()".
Also, if a func logically is an attribute of another, then probably you're
close to defined an object, possibly with other attributes. Think at the design
of the application.
I may be wrong, but I guess the only common case where you should (and must)
define a func inside another is the one of a func factory, ie a func that
defines (and returns) a new func:
def makeAdder(val):
def adder(x):
return x + adder.val
adder.val = val
return adder
add3 = makeAdder(3)
print add3(2) # --> 5
Denis
________________________________
la vita e estrany
http://spir.wikidot.com/
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor