Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Mixin - Unresolved Attribute Reference [PyCharm]

I am using a mixin to separate a range of functionality to a different class. This Mixin is only supposed to be mixable with the only child class:

class Mixin:
    def complex_operation(self):
        return self.foo.capitalize()

class A(Mixin):
    def __init__(self):
        self.foo = 'foo'

in my method Mixin.complex_operation PyCharm gives warning 'Unresolved Attribute Reference foo'.

Am I using the mixin pattern correctly? Is there a better way? (I would like to have type hints and autocompletion in my mixins, and I would like to have multiple mixins.)

like image 279
ikamen Avatar asked Mar 17 '19 17:03

ikamen


2 Answers

Declare the necessary fields in the Mixin like:

class Mixin:
    foo: str

    def complex_operation(self):
        return self.foo.capitalize() 

This way the mixin actually declares the fields a class must have to be able to use this mixin. Type hint will create warnings if extending class will put incompatible type into declared field.

edit: Replaced foo = None with foo:str as suggested by @valex

like image 64
ikamen Avatar answered Nov 14 '22 07:11

ikamen


I see few options.

1) Type annotations (i think this is cleanest solution):

class Mixin:
    foo: str

    def complex_operation(self):
        return self.foo.capitalize()

2) Default None (@ikamen option):

class Mixin:
    foo = None

    def complex_operation(self):
        return self.foo.capitalize()

3) Suppress unresolved reference error for class or for specific line (i think this is more dirty way than first two):

# noinspection PyUnresolvedReferences
class Mixin:
    def complex_operation(self):
        return self.foo.capitalize()
class Mixin:
    def complex_operation(self):
        # noinspection PyUnresolvedReferences
        return self.foo.capitalize()
like image 6
valex Avatar answered Nov 14 '22 08:11

valex