Best place for a function?

Diez B. Roggisch deets at nospam.web.de
Wed Mar 7 23:30:10 CET 2007


Sergio Correia schrieb:
> I'm writing a class, where one of the methods is kinda complex. The
> method uses a function which I know for certain will not be used
> anywhere else. This function does not require anything from self, only
> the args passed by the method.
> 
> Where should I put the function?
> 
> a) Inside the module but outside the class (to avoid cluttering it;
> besides the function does not require to access any property or method
> of the class).
> 
> # mymodule.py
> 
> def  _myfunction():
>     ...
> 
> class myclass(object):
>     def mymethod(self):
>          ...
>          spam = _myfunction()
>    ...
> 
> 
> b) Inside the class but outside the method
> 
> # mymodule.py
> 
> class myclass(object):
>     def  _myfunction(self):
>         ...
> 
>     def mymethod(self):
>          ...
>          spam = self._myfunction()
>    ...
> 
> c) Inside the method:
> 
> # mymodule.py
> 
> class myclass(object):
>     ...
>     def mymethod(self):
>         def  _myfunction(self):
>                   ...
>         ...
>         spam = self._myfunction()
>     ...
> 
> 
> I'm new to python (and couldn't find anything about this in PEP 8).
> What would you suggest me?

If it really has no other use as in this class, put it as an 
instancemethod in there. Alternatively, you _could_ nest it like this:

class Foo(object):

    def bar(self):
        def my_long_important_method(argument):
            pass
        pass


Diez



More information about the Python-list mailing list