相关疑难解决方法(0)

作为**解包的映射的python类

如果没有子类化dict,那么类需要被视为一个映射,以便它可以传递给**的方法

from abc import ABCMeta

class uobj:
    __metaclass__ = ABCMeta

uobj.register(dict)

def f(**k): return k

o = uobj()
f(**o)

# outputs: f() argument after ** must be a mapping, not uobj
Run Code Online (Sandbox Code Playgroud)

至少到它抛出缺少映射功能的错误,所以我可以开始实现.

我查看了模拟容器类型,但只是定义魔术方法没有效果,并且使用ABCMeta覆盖并将其注册为dict将断言验证为子类,但是失败是isinstance(o,dict).理想情况下,我甚至不想使用ABCMeta.

python mapping class argument-unpacking

57
推荐指数
2
解决办法
7269
查看次数

如何在Python 3.8+和Python 2.7中使用collections.abc

在Python 3.3中,collections(如MutableMappingMutableSequence)中的“抽象基类” 被移至了第二级模块collections.abc。因此,在Python 3.3+中,实际类型为collections.abc.MutableMapping依此类推。文档指出,旧别名(例如collections.MutableMapping)将在Python 3.7(当前为最新版本)中可用,但是在3.8中将删除这些别名。

当您使用别名时,当前版本的Python 3.7甚至会产生警告:

./scripts/generateBoard.py:145: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
  elif isinstance(value, (collections.MutableMapping, collections.MutableSequence)) == True:
Run Code Online (Sandbox Code Playgroud)

在python 2.7中没有collections.abc

当Python脚本打算(几乎)与任何Python版本一起使用时,如何以最便捷的方式处理这种差异?我正在寻找一种解决方案,理想情况下可以在一个中央位置解决此混乱情况,而不必try: ... except: ...在需要这种类型的所有地方都使用整个脚本?

python python-2.7 python-3.x

12
推荐指数
3
解决办法
7480
查看次数