Determine the type of an object?

后端 未结 13 2189
余生分开走
余生分开走 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:16

    As an aside to the previous answers, it's worth mentioning the existence of collections.abc which contains several abstract base classes (ABCs) that complement duck-typing.

    For example, instead of explicitly checking if something is a list with:

    isinstance(my_obj, list)
    

    you could, if you're only interested in seeing if the object you have allows getting items, use collections.abc.Sequence:

    from collections.abc import Sequence
    isinstance(my_obj, Sequence) 
    

    if you're strictly interested in objects that allow getting, setting and deleting items (i.e mutable sequences), you'd opt for collections.abc.MutableSequence.

    Many other ABCs are defined there, Mapping for objects that can be used as maps, Iterable, Callable, et cetera. A full list of all these can be seen in the documentation for collections.abc.

提交回复
热议问题