python supports type hints:
https://docs.python.org/3/library/typing.html
I was wondering if these hints can also be used to dynamically enforce types during runtime.
For example:
class C:
def __init__(self):
self.a : int = 0
def __str__(self):
return str(self.a)
@classmethod
def get(cls,**kwargs):
c = cls()
for k,v in kwargs.items():
setattr(c,k,v)
# ValueError exception thrown here ?
return c
attrs = {"a":"a"} # developer wanted an int !
c = C.get(**attrs)
print(c)
In short, I'd like to avoid to re-enter the type of the attribute "a" in the get function:
@classmethod
def get(cls,**kwargs):
c = cls()
for k,v in kwargs.items():
if k=="a" and not isinstance(v,int):
raise ValueError()
setattr(c,k,v)
return c
Would there be a way to "reuse" the information given in the constructor that "a" is expected to be an int ?
Note: answer to this question shows that at least for functions introspection on the arguments type hints can be accessed: