Hey there. I'm not a python developer, and occasionally I need to code in it a bit. One thing I really need hard is proper compile time checks. So I got pyright (a surprisingly good piece of software) and am using it to check the type errors.
Question 1: dynamic attributes
Apparently in python you might be expected to add some attributes to an existing object on the fly. At least that's what the framework in our project expects.
The problem is, I can't find a way to specify the type:
a.x = 4
a.x = None
This fails with an error in the second line: you cannot assign None to int.
Even doing this doesn't help:
x: Optional[int] = 4
a.x = x
a.x = None
Question 2: generic constraints for multiple types
I hear there's no proper multiple generic constraints in python. For example, I might want to define a trait/contract/type class which has a method, and constrain T to it and a few more "traits". What is the python way of doing it?
It doesn't like this syntax (it doesn't like the '+' in the constraints and I couldn't find a better way)
class IQuack:
def quack(self):
pass
class IBark:
def bark(self):
pass
def quack_and_bark[T: IQuack + IBark](x: T):
x.quack()
x.bark()
Question 3: generic constraints for self-referential generics
Pretty classic stuff:
class IAdd[T]:
@abstractmethod
def add(self, y: T) -> T:
pass
def quack_and_bark[T: IAdd[T]](x: T) -> T:
return x.add(x)
It says T in the constraint can't be determined because it refers to itself. How do you do it?
Also feel free to share your tips in this area, I'm all ears. Thanks.


