Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16773

How to properly inherit from dataclass with base instance re-usage

$
0
0

Consider the following:

@dataclassclass Base:  prop1: str  prop2: str@dataclassclass Derived1(Base):  isValid: bool = self.prop2.casefold() == 'valid'@dataclassclass Derived2(Base):  isOpen: bool = self.prop1.casefold() == 'open'  isShared :bool

In this particular example, baseclass it just 2 props, but imagine it is 773 props just for argument sake.Something, somewhere, you dont care what and where, returns you an instance of Base. Now, you may want to promote it to Derived1, keeping all the existing values. Normally, as far as I know, if I want to an instance of a Derived1 or Derived2 class id have to initialize this instance and then manually write assigned in Derived's __init__ or __post_init__ for all the 773 props. It is madness. After some re-search I found a great suggestion that solves this. Instead I use normal class and update props from existing base instance via __dict__ trick:

class Derived(Base):    isOpen: bool = False    def __init__(self, base: Base):        self.__dict__.update(base.__dict__)        self.isOpen = (str(base.currStatus).casefold() == 'open')

While this seems to be working just fine I keep getting a hard error from pylint that there needs to be super. And this is what I'm confused about - do I need need a super here? The issue is that with super I'm back to square one where I have to re-init all 700+ props manually... which is what I wanted to avoid in a first place.

This whole thing seems incredibly silly - this is python we are talking about, I easily can see it having this problem when it comes to classes (which some other languages solved 30 years ago).


Viewing all articles
Browse latest Browse all 16773

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>