1

Is there some type checking API from python3.5 typing that I can use to check nested types in runtime. For example:

from typing import List
check_type([1,2,3], List[int]) # True
check_type([1,2,''], List[int]) # False

This is only example (it can be 3 or more levels nested, have List, Tuple, Dict)

Ivan Borshchov
  • 3,036
  • 5
  • 40
  • 62
  • No but you can implement it pretty easily: `def check_type(li, inner_type): return isinstance(li, list) and all(isinstance(obj, inner_type) for obj in li)` – DeepSpace Aug 15 '17 at 12:27
  • maybe this helps: http://mypy-lang.org/? or check out any of the other references at the bottom of the [PEP 484](https://www.python.org/dev/peps/pep-0484/). – hiro protagonist Aug 15 '17 at 12:27

1 Answers1

1

You can use all() built-in function like below:

def check_type(iterable, tp):
    return all(isinstance(item, tp) for item in iterable)

Output:

>>> check_type([1, 2, 3], int)
True
>>>
>>> check_type([1, 2, ''], int)
False
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • 2
    [`isinstance` is recommend over `type`](https://docs.python.org/3/library/functions.html#type) - _"The `isinstance()` built-in function is recommended for testing the type of an object, because it takes subclasses into account."_. – Christian Dean Aug 15 '17 at 12:28
  • sorry, iterable is only example, just for simplify the question. In real structure can be complex, so I thought I can call something without manual falling to the bottom of structure – Ivan Borshchov Aug 15 '17 at 12:30
  • @ChristianDean Thanks! I updated my answer. – ettanany Aug 15 '17 at 12:32
  • @user3479125 How does you data structure look like? – ettanany Aug 15 '17 at 12:35