Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.7: Inheriting list, abstract ignored [duplicate]

The following does not raise:

from abc import ABCMeta, abstractmethod
class Test(list, metaclass=ABCMeta):
    @abstractmethod
    def test(self):
        pass
test = Test()

although this does:

from abc import ABCMeta, abstractmethod
class Test(metaclass=ABCMeta):
    @abstractmethod
    def test(self):
        pass
test = Test()

Is this a known problem? What can I do to fix it? I need to inherit from something that looks exactly like a list and create an abstract inheritor. Thank you.

like image 662
Vasilis Lemonidis Avatar asked Nov 30 '18 14:11

Vasilis Lemonidis


1 Answers

I think the issue here is that you should not inherit directly fromlist. There are some wrapper classes for doing this in collections. In this case UserList:

from abc import ABCMeta, abstractmethod
from collections import UserList
class Test(UserList, metaclass=ABCMeta):
    @abstractmethod
    def test(self):
        pass
test = Test()

Here you have the live example from:

class Test1(Test):
  def test(self):
    print("foo")

test = Test1()
test.append(10)
test.test()
print(test)

Results:

foo
[10]
like image 66
Netwave Avatar answered Oct 26 '22 23:10

Netwave