I built a custom list-like class based on 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?
No, there is no way instances of your class can pass that test without inheriting from list
. You have to subclass list
to pass that test.
You can try inheriting from both MutableSequence
and 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:
class MyList(collections.MutableSequence, list):
You could also monkeypatch the check_correct_type()
function, provided it really is a stand-alone function like that:
def my_check_correct_type(value):
assert isinstance(value, collections.MutableSequence)
third_party_library.check_correct_type = my_check_correct_type