Coding Style: Defining Functions within Methods?

Harry Pehkonen harry.pehkonen at hotpop.com
Fri Sep 5 12:37:05 EDT 2003


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