Coding Style: Defining Functions within Methods?
Bengt Richter
bokr at oz.net
Fri Sep 5 17:57:48 EDT 2003
On 5 Sep 2003 09:37:05 -0700, harry.pehkonen at hotpop.com (Harry Pehkonen) wrote:
>I have been defining new class methods when I'm trying to simplify
>some code. But I'm thinking I should just define functions within
>that method because they aren't useful from the outside anyway.
>Example:
>
>
>Before:
>
>class Mess(object):
> def complicated(self, count):
> for i in count:
> self.do_loop(i)
> def do_loop(self, i):
> ...whatever...
>
>
>After:
>
>class Cleaner(object):
> def complicated(self, count):
> def do_loop(i)
> ...whatever...
> for i in count:
> do_loop(i)
>
>The point is that do_loop is now not ``contaminating'' things. I
>suppose do_loop could be __do_loop, but it would still show up in
>places where I don't think it should (such as dir(Mess)).
>
>Thoughts?
I like defining nested functions except for the fact that a definition is executable code
in itself, and will be re-executed each time the outer function or method is called. I'm
not sure how long MAKE_FUNCTION or MAKE_CLOSURE take to execute, but IWT it must mean allocating
and glueing together the dynamic elements necessary for a distinct function/closure instance,
and then disposing of them at some point on/after their going out of scope, vs. e.g. just locating
a sibling method.
OTOH, the outer overhead may become relatively insignificant if the inner is called boocoo times
in a loop and/or recursively.
On the third hand, clear code will outweigh any performance issues for much code.
Regards,
Bengt Richter
More information about the Python-list
mailing list