Search code examples
pythonpython-3.xtype-hinting

What is the type hint for built-in types


I'm writing a function that receives a type as a parameter (similar to isinstance).
What should be the type-hint so that users have a clear idea of what the parameter is?

For example, what would be the type of classinfo below if isinstance had type hints?

def isinstance(object: Any, classinfo: _____):
    pass

EDIT: pending a long discussion, adding the code to the actual function:

I'm traversing a JSON object and executing a Callable on a specific type. I want the users of this function to have an easy time understanding what the execute_on_type parameter is.

def traverse_json_obj(jobj: list or dict, callable: Callable, execute_on_type: __??__):
    if isinstance(jobj, execute_on_type):
        yield callable(jobj)
    if isinstance(jobj, dict):
        for _, v in jobj.items():
            if isinstance(v, execute_on_type):
                yield callable(v)
            else:
                for child_res in traverse_json_obj(v, callable, execute_on_type):
                    yield child_res
    elif isinstance(jobj, list):
        for item in jobj:
            for item_val in traverse_json_obj(item, callable, execute_on_type):
                yield item_val

Then the following:

jobj = {'id': {'num': 1, 'str': 'two'}, 'list': [{'num': 3, 'str': 'four', 'list': [5, 6]}]}
list(traverse_json_obj(jobj, print, int))

should yield

1
3
5
6

Solution

  • The second argument to isinstance is one of three things:

    1. A type
    2. A tuple
    3. (In Python 3.10 or later) a typing.Union.

    The problem is that not just any tuple is allowed: each element of the tuple must be one of the three things listed above, leading to a recursively defined type. Essentially, it's a "tree" of types built with tuples (and Unions). I'm not sure how, or even if, you can represent such a type using the typing module. Prior to Python 3.10, you could write

    TypeTuple = typing.Union[type, typing.Tuple['TypeTuple',...]]
    

    though mypy's ability to use such a hint is (or was) limited.