i playing around bit new type hinting / typing module python3.5 trying find way confirm if hinted type equal actual type of variable , came across rather surprised me.
>>> typing import list >>> somelist = [1, 2, 3] >>> isinstance(somelist, list[str]) true
continuing search finding way compare variable it's hinted type i've tried this:
>>> anotherlist = ["foo", "bar"] >>> type(anotherlist) list[str] false
would able explain why former evaluates true?
and continuing onwards, there sound way check if variable's type equal type coming typing module?
isinstance
not real pep 484 type checking. the documentation notes in passing:
in general,
isinstance()
,issubclass()
should not used types.
the typing
module, collections.abc
, abc
modules it’s based on, use extensive __instancecheck__
, __subclasscheck__
magic make isinstance
, issubclass
behave reasonably. they’re not doing enough support case. nor goal support it.
is there sound way check if variable's type equal type coming typing module?
you’re not looking type equality. have noted yourself, type of [1, 2, 3]
list
, not equal list[str]
, nor list[int]
. you’re looking type checking, more complicated.
consider this:
def my_function(): # ... 1000 lines of complicated code ... print(isinstance(my_function, callable[[], int]))
what expect program print? can’t expect isinstance
dig my_function
@ runtime , infer returns int
. not feasible in python. need either “compile” time type checker has access structure of my_function
, or explicit type annotations, or—most likely—both.
Comments
Post a Comment