I'm using code such as this to add properties dynamically to a class:
class A:
def __init__(self, props) -> None:
for name in props:
setattr(self.__class__, name, property(lambda _: 1))
This will work as expected:
A(["x"]).x # outputs 1
However, Pylance (at least in vscode) will (understandably) complain with Cannot access member "x" for type "A" Member "x" is unknown
.
Is there a way to help Pylance understand what is going on?
Note: Adding the properties to __annotations__
doesn't help, the warning remains:
class A:
def __init__(self, props) -> None:
self.__class__.__annotations__ = {}
for name in props:
setattr(self.__class__, name, property(lambda _: 1))
self.__class__.__annotations__[name] = int
Variant B:
What if the code was less dynamic, like so?
class A:
PROPS = ["x", "y", "z"]
def __init__(self) -> None:
for name in self.PROPS:
setattr(self.__class__, name, property(lambda _: 1))
Any chance to help Pylance in this scenario?