Typehinting an extendable class #7321
              
                Unanswered
              
          
                  
                    
                      ItsCubeTime
                    
                  
                
                  asked this question in
                Q&A
              
            Replies: 1 comment 7 replies
-
| I'm not sure I fully understand the proposed code structure, but it sounds like you want to leverage some form of polymorphism — i.e. functions that return different types depending on various context. The Python type system has several mechanisms to support polymorphism. One commonly-used tool is an overload, which you can read about here. Another available tool is generics — the use of type variables to represent stand-in types. You can read about generics here. | 
Beta Was this translation helpful? Give feedback.
                  
                    7 replies
                  
                
            
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I'm writing an html generator that uses Python classes to represent html elements.
I have a base class
HtmlGenwith several child classes, such asHtmlGen_Text,HtmlGen_Button,HtmlGen_Checkbox(etc).An html structure is built like so:
Currently I implement this by creating the text/button/checkbox attributes inside
HtmlGen.__init__(): ...(which all other classes inherit, allowing recursive use as demonstrated by me putting text inside the button on the last line in the snippet above).My dilemma is now that I want to be able to create custom styling for each and every element type. To do this, I was thinking to allow subclassing of each child class, eg:
class HtmlGen_PinkText(HtmlGen_Text): css=".p {color:pink;}", subclassHtmlGen:class HtmlGenExtended: def __init__(self): super().__init__(); self.pinkText=HtmlGen_PinkTextand then do some magic inside the__new__method to make sure all instances created fromHtmlGenExtendedvia its attributes will inherit fromHtmlGenExtendedinstead ofHtmlGen.The issue is, how could I then allow type hinting for syntax like
he=HtmlGenExtended(); he.pinkText(...), without modifying the source code of the originalHtmlGen? Is it possible at all? Any thoughts would be highly appreciated :) Currently all I can think of would be creating a build system that creates Python source code on the fly just for the type hinting (which would then have to copy every single class living as an attribute onHtmlGen, make them inherit fromHtmlGenExtendedinstead & place them as attributes on a 3rd class used solemnly for type hinting alongside the attributes ofHtmlGenExtended).Beta Was this translation helpful? Give feedback.
All reactions