QuEraComputing / bloqade-python

QuEra's Neutral Atom SDK for Analog QPUs
https://bloqade.quera.com/
Other
53 stars 14 forks source link

Replace mix-in traits with Decorators for proper type checking #559

Open weinbe58 opened 12 months ago

weinbe58 commented 12 months ago

Playing around a bit with MyPy and I have found that the the standard way of doing mix-in traits doesn't quite work with type checking. Take the following example

from typing import Any

class OtherClass:
    def method(self, other: "MyClass") -> Any:
        return None

class Trait:
    def my_method(self) -> Any:
        return OtherClass().method(self)

class MyClass(MyTrait):
    pass

gives the following error:

main.py:9: error: Argument 1 to "method" of "OtherClass" has incompatible type "Trait"; expected "MyClass" [arg-type] Found 1 error in 1 file (checked 1 source file)

And you can't annotate the self in the Trait because that creates another issue with type checking.

I think the only solution for this is to use a decorator to inject that method into MyClass

from typing import Any

class OtherClass:
    def method(self, other: "MyClass") -> Any:
        return None

def add_trait(cls):
    def method(self, other: "MyClass") -> Any:
        return OtherClass().method(other)

    setattr(cls, "method", method)

@add_trait
class MyClass:
    pass
weinbe58 commented 11 months ago

Actually this also could work: https://docs.python.org/3/library/abc.html