Determine the type of an object?

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

    You can use type() or isinstance().

    >>> type([]) is list
    True
    

    Be warned that you can clobber list or any other type by assigning a variable in the current scope of the same name.

    >>> the_d = {}
    >>> t = lambda x: "aight" if type(x) is dict else "NOPE"
    >>> t(the_d) 'aight'
    >>> dict = "dude."
    >>> t(the_d) 'NOPE'
    

    Above we see that dict gets reassigned to a string, therefore the test:

    type({}) is dict
    

    ...fails.

    To get around this and use type() more cautiously:

    >>> import __builtin__
    >>> the_d = {}
    >>> type({}) is dict
    True
    >>> dict =""
    >>> type({}) is dict
    False
    >>> type({}) is __builtin__.dict
    True
    

提交回复
热议问题