[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Pylint false positives

On Sun, Aug 19, 2018 at 10:28 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
>> On Sun, 19 Aug 2018 11:43:44 +0300, Marko Rauhamaa wrote:
>>> At least some of the methods of inner classes are closures (or there
>>> would be no point to an inner class).
>> [...]
>> (2) Whether or not the methods of an inner class are closures depends on
>> the methods, not the fact that it is an inner class. There are no
>> closures here:
>>     class Outer:
>>         class Inner:
>>            ...
>> no matter what methods Inner has. Nor is this a closure:
>>     class Outer:
>>         def method(self):
>>             class Inner:
>>                 def spam(self):
>>                     return self.eggs
>>             return Inner
> The most useful use of inner classes is something like this:
>     class Outer:
>         def method(self):
>             outer = self
>             class Inner:
>                 def spam(self, a, b):
>                     outer.quarantine(a, b)
>             return Inner()

That's pretty inefficient. I'm not sure what you gain by having Inner
be local to that method, but here's what you lose:

1) Each instance of Inner carries with it a large class object.
2) You can't identify these objects as being of the same type (since
they're not).
3) Every invocation of method() has to execute the class body, which takes time.

At the price of a very small amount of encapsulation, you can make it
actually an inner class:

    class Outer:
        class Inner:
            def __init__(self, outer):
                self.spam = outer.quarantine

        def method(self):
            return self.Inner(self)

Now all instances of Inner are actually instances of the same type.
It's still local to the class, just not local to that method.

None of this explains your aversion to creating functions in a loop at
class scope, while still being perfectly happy doing so at function