Reputation: 407
I'm trying to use type hints. My tests so far allow defining type hints but they do not seem to be enforced.
from typing import Type,TypeVar
MyType=TypeVar("MyType",bound="my")
class my:
@staticmethod
def factory(test) -> MyType:
if test==1:
return my(1)
if test==2:
return Exception("what am I")
return None
def __init__(self,thevar):
self.test=thevar
def typecheck(var: MyType):
print("function called with type %s" % type(var))
myclass=my("")
for test in range(0,3):
thevar=my.factory(test)
print ("My type is %s" % type(thevar))
my.typecheck(thevar)
I am expecting errors to be raised when the wrong type is passed or returned. Except perhaps for when a None is returned instead of a class
Upvotes: 2
Views: 1200
Reputation: 2301
As Aaron mentioned, this is usually done with another tool (mypy), rather than the python interpreter.
To install mypy (from the docs):
$ python3 -m pip install mypy
Then, to type check your code with mypy:
$ mypy program.py
Upvotes: 4