有没有一种简单的方法来确定变量是列表、字典还是其他什么?


当前回答

在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。

换句话说,当您有如下代码时,您可能希望使用它:

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

下面是一个工作原理的小示例:

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 <class 'dict'>

此外,我们可以使用抽象类同时覆盖几种类型:

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!

其他回答

在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。

换句话说,当您有如下代码时,您可能希望使用它:

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

下面是一个工作原理的小示例:

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 <class 'dict'>

此外,我们可以使用抽象类同时覆盖几种类型:

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!
value = 12
print(type(value)) # will return <class 'int'> (means integer)

或者你可以这样做

value = 12
print(type(value) == int) # will return true

在对象的实例上,还具有:

__class__

属性下面是一个来自Python3.3控制台的示例

>>> str = "str"
>>> str.__class__
<class 'str'>
>>> i = 2
>>> i.__class__
<class 'int'>
>>> class Test():
...     pass
...
>>> a = Test()
>>> a.__class__
<class '__main__.Test'>

请注意,在python3.x和NewStyle类(可从Python2.6中选择)中,类和类型已经合并,这有时会导致意外的结果。主要是因为这个原因,我最喜欢的测试类型/类的方法是使用内置函数。

确定Python对象的类型

使用类型确定对象的类型

>>> obj = object()
>>> type(obj)
<class 'object'>

虽然它有效,但避免使用__class__之类的双下划线属性-它们在语义上不是公共的,虽然在这种情况下可能不是,但内置函数通常具有更好的行为。

>>> obj.__class__ # avoid this!
<class 'object'>

类型检查

有没有一种简单的方法来确定变量是列表、字典还是其他什么?我得到了一个可能是这两种类型的对象,我需要能够分辨出其中的区别。

好吧,这是另一个问题,不要使用类型-用法:

def foo(obj):
    """given a string with items separated by spaces, 
    or a list or tuple, 
    do something sensible
    """
    if isinstance(obj, str):
        obj = str.split()
    return _foo_handles_only_lists_or_tuples(obj)

这涵盖了这样一种情况,即您的用户可能正在通过子类化str来做一些聪明或明智的事情-根据Liskov Substitution的原理,您希望能够在不破坏代码的情况下使用子类实例-而isinstance支持这一点。

使用摘要

更好的是,您可以从集合或数字中查找特定的抽象基类:

from collections import Iterable
from numbers import Number

def bar(obj):
    """does something sensible with an iterable of numbers, 
    or just one number
    """
    if isinstance(obj, Number): # make it a 1-tuple
        obj = (obj,)
    if not isinstance(obj, Iterable):
        raise TypeError('obj must be either a number or iterable of numbers')
    return _bar_sensible_with_iterable(obj)

或只是不显式键入检查

或者,也许最棒的是,使用duck类型,不要显式地检查代码类型。Duck类型支持Liskov替换,更优雅,更少冗长。

def baz(obj):
    """given an obj, a dict (or anything with an .items method) 
    do something sensible with each key-value pair
    """
    for key, value in obj.items():
        _baz_something_sensible(key, value)

结论

使用类型实际获取实例的类。使用isinstance显式检查实际的子类或注册的抽象。只要在有意义的地方避免类型检查。

可以使用type()或isinstance()。

>>> type([]) is list
True

请注意,通过在当前作用域中分配同名变量,可以删除列表或任何其他类型。

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

上面我们看到dict被重新分配给一个字符串,因此测试:

type({}) is dict

…失败。

要解决此问题并更谨慎地使用type():

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