Coding Style: Defining Functions within Methods?

JCM joshway_without_spam at myway.com
Fri Sep 5 18:42:47 CEST 2003


Generally I also find it cleanest to push functions down into the most
nested scope possible; it makes it clear that these are helper
functions and not meant to be called externally.

Harry Pehkonen <harry.pehkonen at hotpop.com> 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?

> Thanks!
> Harry.




More information about the Python-list mailing list