1

If I have a script like:

class ClassA(object):
    ...
    def methodA(...):
        varA=...

        def funcA(...):
            ...

        varA=funA(...)

I mean I intend to write a small function inside a class method, which is only used inside this class method. Is this code style OK? I think it's a little ugly. Is there alternate?

ThunderEX
  • 703
  • 1
  • 7
  • 13
  • 1
    One potential problem is that you'll be re-defining `funcA` every time `methodA` is called. – Blender Dec 21 '12 at 06:55
  • Have you considered using a lambda function instead? – Martin Green Dec 21 '12 at 06:56
  • @Blender then how can I avoid re-defining funcA? – ThunderEX Dec 21 '12 at 06:59
  • @ThunderEX: By defining it outside of `methodA`. – Blender Dec 21 '12 at 07:00
  • Why are you doing it this way? Do you have a reason for putting funcA inside `methodA` instead of elsewhere (or just doing its operations directly in the body of `methodA`)? – BrenBarn Dec 21 '12 at 07:02
  • @BrenBarn because in this way it seems clearer that funA only works for methodA – ThunderEX Dec 21 '12 at 07:07
  • @ThunderEX: But then what is the point of making it a function? Why not just put its contents directly into `methodA`? – BrenBarn Dec 21 '12 at 07:13
  • @BrenBarn Because that piece of code is frequently used in the method – ThunderEX Dec 21 '12 at 07:17
  • 1
    See [this question](http://stackoverflow.com/questions/13984818/limit-a-method-to-be-called-only-through-another-method/13984872#13984872) from just an hour ago for some discussion. – BrenBarn Dec 21 '12 at 07:19
  • @BrenBarn nice! i am going to keep its original style now. – ThunderEX Dec 21 '12 at 07:26
  • @ThunderEX, I would only do this if the function really does need to be nested, e.g. if it accesses some variables from the scope of the enclosing method, or if you need different defaults each time (though `partial` may be preferable in the second instance). However, in that situation it is perfectly fine. Don't worry about redefining the function every time the method is called: function definitions are no more expensive than any other object creation. – Duncan Dec 21 '12 at 09:52

1 Answers1

1

Beauty is in the eye of the beholder.

It is totally fine having a very "local" function nested inside another function - especially from the point of readability of code.

Others will argue with coding style and best practice.

It is your code and you must feel fine with your code in order to understand and read it later.

So if it is fine for you and your understanding of "nice" code, go ahead.