Horrible abuse of __init_subclass__, or elegant hack?

Chris Angelico rosuav at gmail.com
Wed Mar 31 20:54:24 EDT 2021


On Thu, Apr 1, 2021 at 11:39 AM dn via Python-list
<python-list at python.org> wrote:
>
> 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']

Real and imaginary are the same thing, just rotated a quarter turn....

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

Perhaps, but there are potentially a LOT of recipes, and I needed to
be able to cleanly edit those, even if the code at the top was a mess.
(The goal here is to map out production patterns in the game
"Satisfactory", for the curious. It's easy to add other things, like
computer manufacturing or bauxite processing, simply by adding more
recipes.)

My original plan was basically pairwise tuple summing (deriving a set
of "oil in, water in, rubber out, fuel out" for each set of recipes,
where some might be zero), but it turned out that that wasn't flexible
enough, and it really needed more options than that.

> As to this, I'm slightly amused, but perhaps not in a good way:
>
> class Sanatorium( Building ):
>    patient_name = "Chris"
>    duration_of_treatment = "life"

I already have certificates from Rutledge's Asylum and MaayaInsane's
(unnamed) asylum, so that seems pretty likely.

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

Perfect. Nobody'll find it. I'll have full access to Usenet News from
a secret panel in one of the padded sections of the wall.

ChrisA


More information about the Python-list mailing list