Coverage for C:\Users\hjanssen\HOME\pyCharmProjects\ethz_hvl\hvl_ccb\hvl_ccb\utils\typing.py: 86%

# Coverage for C:\Users\hjanssen\HOME\pyCharmProjects\ethz_hvl\hvl_ccb\hvl_ccb\utils\typing.py : 86%

## 21 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1# Copyright (c) 2019-2020 ETH Zurich, SIS ID and HVL D-ITET

2#

3"""

4 Additional Python typing module utilities

5"""

6 import sys

7 from typing import Union

8

9 from typeguard import origin_type_checkers # type: ignore

10

11 if sys.version_info >= (3, 9):

12 from types import GenericAlias # PEP 585

13

14

15 def is_generic_type_hint(type_):

16 """

17 Check if class is a generic type, for example `Union[int, float]`, `List[int]`, or

18 `List`.

19

20 :param type_: type to check

21 """

22

23 if not (sys.version_info >= (3, 9) and isinstance(type_, GenericAlias)):

24

25 if not hasattr(type_, "__module__"):

26 return False

27

28 # check if the class inherits from any `typing` class

29 if type_.__module__ != "typing":

30 if not any(t.__module__ == "typing" for t in type_.mro()):

31 return False

32

33 origin = getattr(type_, "__origin__", type_) # Note: List.__origin__ == list

34

35 return origin in origin_type_checkers

36

37

38 def check_generic_type(value, type_, name="instance"):

39 """

40 Check if `value` is of a generic type `type_`. Raises `TypeError` if it's not.

41

42 :param name: name to report in case of an error

43 :param value: value to check

44 :param type_: generic type to check against

45 """

46 if not hasattr(type_, "__origin__") or type_.__origin__ not in origin_type_checkers:

47 raise ValueError("Type {} is not a generic type.".format(type_))

48 origin_type_checkers[type_.__origin__](name, value, type_, None)

49

50

51 Number = Union[int, float]

52"""Typing hint auxiliary for a Python base number types: `int` or `float`."""