Determine the type of an object?

后端 未结 13 2346
余生分开走
余生分开走 2020-11-22 05:50

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 06:10

    In many practical cases instead of using type or isinstance you can also use @functools.singledispatch, which is used to define generic functions (function composed of multiple functions implementing the same operation for different types).

    In other words, you would want to use it when you have a code like the following:

    def do_something(arg):
        if isinstance(arg, int):
            ... # some code specific to processing integers
        if isinstance(arg, str):
            ... # some code specific to processing strings
        if isinstance(arg, list):
            ... # some code specific to processing lists
        ...  # etc
    

    Here is a small example of how it works:

    from functools import singledispatch
    
    
    @singledispatch
    def say_type(arg):
        raise NotImplementedError(f"I don't work with {type(arg)}")
    
    
    @say_type.register
    def _(arg: int):
        print(f"{arg} is an integer")
    
    
    @say_type.register
    def _(arg: bool):
        print(f"{arg} is a boolean")
    
    >>> say_type(0)
    0 is an integer
    >>> say_type(False)
    False is a boolean
    >>> say_type(dict())
    # long error traceback ending with:
    NotImplementedError: I don't work with 
    

    Additionaly we can use abstract classes to cover several types at once:

    from collections.abc import Sequence
    
    
    @say_type.register
    def _(arg: Sequence):
        print(f"{arg} is a sequence!")
    
    >>> say_type([0, 1, 2])
    [0, 1, 2] is a sequence!
    >>> say_type((1, 2, 3))
    (1, 2, 3) is a sequence!
    

提交回复
热议问题