Horrible abuse of __init_subclass__, or elegant hack?

dn PythonList at DancesWithMice.info
Wed Mar 31 20:37:50 EDT 2021


On 01/04/2021 12.14, Chris Angelico wrote:
> I think this code makes some sort of argument in the debate about
> whether Python has too much flexibility or if it's the best
> metaprogramming toolset in the world. I'm not sure which side of the
> debate it falls on, though.
> 
> class Building:
>     resource = None
>     @classmethod
>     def __init_subclass__(bldg):
>         super().__init_subclass__()
>         print("Building:", bldg.__name__)
>         def make_recipe(recip):
>             print(recip.__name__.replace("_", " "), "is made in a",
> bldg.__name__.replace("_", " "))
>         bldg.__init_subclass__ = classmethod(make_recipe)
> 
> 
> class Extractor(Building): ...
> class Refinery(Building): ...
> 
> class Crude(Extractor):
>     resource = "Oil"
>     time: 1
>     Crude: 1
> 
> class Plastic(Refinery):
>     Crude: 3
>     time: 6
>     Residue: 1
>     Plastic: 2
> 
> class Rubber(Refinery):
>     Crude: 3
>     time: 6
>     Residue: 2
>     Rubber: 2


[pauses for a moment, to let his mind unwind and return to (what passes
as) 'reality']

Without looking into the details/context: surely there's a more
straightforward approach?


As to this, I'm slightly amused, but perhaps not in a good way:

class Sanatorium( Building ):
   patient_name = "Chris"
   duration_of_treatment = "life"


Thus, design suggestion: add a 'back-door' to the __init_subclass__ to
ensure access to the Internet from any/all buildings!
-- 
Regards,
=dn


More information about the Python-list mailing list