等价物abc序列在Python 2中

2024-04-20 06:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把一些python3代码转换成python2代码

from collections.abc import Sequence

def to_tensor(X, device):
  .....
    if isinstance(X, (list, tuple)):
        return [to_tensor_(x) for x in X]

    if isinstance(X,Sequence):<-------equals to if isinstance(X,(str,bytes))?
        X = torch.tensor(np.array(X))

    return X.to(device)

如上所述,我想知道:

isinstance(X,Sequence)

等于

isinstance(X,(str,bytes))

the documentation 对我来说毫无意义。你知道吗


Tags: to代码fromreturnifbytesdevicecollections
1条回答
网友
1楼 · 发布于 2024-04-20 06:10:20

简言之:不,它不是等价的。你知道吗

最长答案:

首先,Python2没有“bytes”类型-Python3bytes是Python2str,Python3str是Python2unicode,所以正确的问题是:isinstance(X,Sequence)是否等价于isinstance(X, (unicode, str))。你知道吗

那么,答案仍然是否定的。Py3 strbytes确实是abc.Sequence的实例,但是实现abc.Sequence的类的任何实例也是Sequence的对象,而不是strbytes(Django orm的Queryset类将是一个完美的候选者)。你知道吗

and this doc: https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence make not no sense to me

如果您遵循本文档中的链接,you get a verbal definition了解什么是“序列”:

An iterable which supports efficient element access using integer indices via the getitem() special method and defines a len() method that returns the length of the sequence (..) Note that dict also supports getitem() and len(), but is considered a mapping rather than a sequence

根据这个定义,要测试一个对象是否是序列,您必须测试它是否是iterable,是否有__getitem____len_方法,并且不是dict。这与py3代码不同,但您可以更接近它(至少在没有更多上下文的情况下,参见下文):

def is_sequence(obj):
    if isinstance(obj, dict):
        return False

    if not (
        hasattr(obj, "__getitem__") 
        and hasattr(obj, "__len__")
        ): 
        return False

    # we might have false postive here
    # with dict-likes not inheriting from
    # `dict`, so we also weed out objects 
    # having a `keys()` methods which
    # are most likely dict-likes
    if hasattr(obj, "keys"):
        return False
    return True

现在,您的问题的真正答案可能有点不同:有“序列”的正式定义(更多或更少),还有调用您移植的代码的上下文和作者的意图。你知道吗

作者可能假设他的函数只会被传递列表、元组、字符串或字节,在这种情况下,测试意图确实是一种错误的(我甚至可以说是中断的)和没有文档记录的尝试来检查字符串和字节。你知道吗

或者作者可能假设他的函数永远不会被传递一个字符串或字节,但是我不明白为什么他会把列表和元组与其他序列区别对待。你知道吗

长话短说:你必须研究上下文,或者最终要求作者澄清——当然,如果可能的话。你知道吗

相关问题 更多 >