[英]MutableSequence to pass as a list in isinstance() check
I built a custom list-like class based on collections.MutableSequence
: 我基于
collections.MutableSequence
构建了一个类似于列表的自定义类:
class MyList(collections.MutableSequence):
etc... behave mostly like a list...
value = MyList([1,2,3])
Before processing list data, a third-party library runs a check: 在处理列表数据之前,第三方库将运行以下检查:
def check_correct_type(value):
assert isinstance(value, list)
I do not wish to convert my custom list-like object to a built-in list before passing it to the third-party library. 我不希望在将其类似列表的自定义对象传递给内置库之前将其转换为内置列表。
Is there an elegant way to make an instance of MyList
appear as though it was an instance of list
in the isinstance(MyList([1,2,3]), list)
check? 有没有一种优雅的方法可以使
MyList
的实例看起来像是isinstance(MyList([1,2,3]), list)
检查中的list
的实例?
No, there is no way instances of your class can pass that test without inheriting from list
. 不,如果没有从
list
继承,您的类实例将无法通过该测试。 You have to subclass list
to pass that test. 您必须继承
list
才能通过该测试。
You can try inheriting from both MutableSequence
and list
; 您可以尝试从
MutableSequence
和list
继承; any method or attribute not implemented by your class or by MutableSequence
will then be looked up on list
, so you may get extra methods that you don't want this way and those may behave unexpectedly: 然后,将在
list
查找未由您的类或MutableSequence
实现的任何方法或属性,因此您可能会得到不需要的其他方法,而这些方法或方法可能会出现异常:
class MyList(collections.MutableSequence, list):
You could also monkeypatch the check_correct_type()
function, provided it really is a stand-alone function like that: 您还可以monkeypatch
check_correct_type()
函数,只要它确实是像这样的独立函数:
def my_check_correct_type(value):
assert isinstance(value, collections.MutableSequence)
third_party_library.check_correct_type = my_check_correct_type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.