0

Is there a way to assert type descriptions at run time?

wishful thinking:

import typing

def work(hours: int, place: str, fruit: List[str]):
    typing.assert(hours, int)
    typing.assert(place, str)
    typing.assert(fruit, List[str])
    ...

typing library

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Leevi L
  • 1,538
  • 2
  • 13
  • 28
  • 2
    Do you want the annotation to *implicitly* mean a runtime assertion, or do you want an *explicit* assertion using manually supplied types? Are you looking for ``assert isinstance(hours, int)``? Note that any non-trivial check such as ``isinstance(fruit, List[str])`` would be painfully slow due to being O(n) or worse. – MisterMiyagi Jan 20 '21 at 17:07
  • 1
    Are you asking how to check the type of an object? `typing` is for *type annotations*, not for runtime type checking – juanpa.arrivillaga Jan 20 '21 at 17:10
  • `List[str]` is not a `type` , it is a type annotation. You'd have to write the logic yourself, or use a library that has implemented this already, like `pydantic`, note, checking a type annotation like `List[str]` would be really inefficient – juanpa.arrivillaga Jan 20 '21 at 17:11
  • So instead, you should probably use a third-party static type checker like `mypy` – juanpa.arrivillaga Jan 20 '21 at 17:19

0 Answers0