Skip to content

Metaclass confusion with properties #7945

Open
@ronaldoussoren

Description

@ronaldoussoren

I'm using python 3.8 and mypy 0.740. The script below prints "21" and "42" when run, but fails to type check with mypy:

class meta (type):
    pass

class value (metaclass=meta):
    pass


class submeta (meta):
    @property
    def attr(cls) -> int:
        return 42

class subvalue (metaclass=submeta):
    @property
    def attr(self) -> int:
        return 21

o = subvalue()
a = o.attr
print(a)
a = subvalue.attr
print(a)

The mypy diagnostics say:

meta-test.py:24: error: Incompatible types in assignment (expression has type "Callable[[subvalue], int]", variable has type "int")
Found 1 error in 1 file (checked 1 source file)

The error is incorrect, "subvalue.attr" has type "int", as it resolves to the property defined on the metaclass, not to the property defined on the class.

This is fairly esoteric as written, but is the structure used by PyObjC to expose Objective-C classes. PyObjC uses metaclasses to expose class methods because ObjC classes can have instance- and class-methods with the same name.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions