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

How to type-hint a link between a class attribute and an instance attribute?

$
0
0

I have the following code:

class ParentClass():"""ParentClass code goes here"""class ParentCategoryClass():"""Subclasses of this class are supposed to regroup instances of one or several ParentClass subclasses"""    elements:dict[str, type[ParentClass]] #This lists the ParentClass subclasses that the category is going to hold    def __init__(self)        self.content:dict[str,ParentClass] = {} #This will be filled later with instances of the classes in elements

I would like to somehow specify that the content attribute will specifically have instances of the ParentClass subclasses that are in elements.

For example, another file could have:

class ChildClass(ParentClass):"""This one is actually going to be instanciated"""class ChildCategoryClass(ParentCategoryClass):"""This one is also going to be instanciated"""    elements: {"child class": ChildClass}    # The values in the content dictionary of a ChildCategoryClass will always be ChildClass instances. But I'm not redefining the __init__, so I can't specify that (plus it would be redundant with the elements attribute).

There could also be several child classes in the elements class attribute.

I tried using TypeVar with the following code:

class ParentClass():"""ParentClass code goes here"""ChildClassVar = TypeVar("ChildClassVar", bound=ParentClass)class ParentCategoryClass():"""Subclasses of this class are supposed to regroup instances of one or several ParentClass subclasses"""    elements:dict[str, type[ChildClassVar]] #This lists the ParentClass subclasses that the category is going to hold    def __init__(self)        self.content:dict[str,ChildClassVar] = {} #This will be filled later with instances of classes in elements

But the linter says ChildClassVar has no meaning in this context. I'm also doubtful this would have worked for several child classes in the first place.

How can I specify that values of the content attribute are always instances of classes among the elements values?


Viewing all articles
Browse latest Browse all 13891

Trending Articles



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