2

So I have a situation where one module writes some code that processes records, so lets say it does this:

from datetime import datetime
def is_record_today(rec: Record) -> bool:
    return (rec.date == str(datetime.now().date()))

def is_record_valid(rec: Record) -> bool:
    return record.is_valid()

so at this time I need to define:

import abc
class Record(abc.ABC):
    @abc.abstractproperty
    def date(self) -> str:
        print('I am abstract so should never be called')
    
    @abc.abstractmethod
    def is_valid(self) -> bool:
        print('I am abstract so should never be called')

now when I am processing a record in another module I want to inherit from this abstract class so I raise an error if I don't have date and is_valid. However, I also want to inherit from another class to get the default properties, lets say I want my record to be manipulatable like a dictionary. Then:

class ValidRecord(Record, dict):
    @property
    def date(self) -> str:
        return self['date']
    def is_valid(self) -> bool:
        return self['valid']

class InvalidRecord(Record, dict):
    @property
    def date(self) -> str:
        return self['date']
   

we would expect that ValidRecord should create without issue and InvalidRecord should throw TypeError, however both seem fine, and I can even call the missing abstractmethod from the Record class which as far as I understand abstract methods should not be possible:

data = {
    'date': '2021-05-01',
    'valid': False
}
InValidRecord(data).is_valid()
>>> "I am abstract so should never be called"

If I take away the dictionary inheritance I get the expected error so, what is going on here and how can I get the desired behavior of inheriting from one class but requiring additional methods be added?

Richard Boyne
  • 327
  • 1
  • 7
  • really interesting find is that if you change `dict` to `collections.UserDict` this works as expected! very odd as [this](https://stackoverflow.com/a/1394572/13665895) comment suggests that `UserDict` only exists for backwards compatibility. – Richard Boyne May 19 '21 at 08:47

0 Answers0