Thursday 21 October 2021

How to add a base class automatically?

Introduction: A package xy defines a Node class (names are not real). Multiple nodes create a graph-like structure that the package does interesting things with. Basic example:

node0 = xy.Node(... some arguments here ...)

Nodes can have optional features. This is currently implemented with add-on/mix-in classes. Something like that:

class NodeF7(xy.Feature7, xy.Node):
    pass

node1 = NodeF7(..., feature7_timeout=5)
  1. the package user can now specify feature7 related values
  2. the package itself enables calls to the feature's methods in its internal code, because isinstance(node1, xy.Feature7) test is true.

Problem: Very often it is necessary to define a new class just to create a single instance of it. I'm thinking about simplifiyng the usage to just:

node1 = xy.Node(..., feature7_timeout=5)

i.e. when the Node class encounters any feature7 related parameter, it should automatically include the Feature7 class add-on. It is important, that isinstance(node1, xy.Feature7) becomes true.

I would like to ask how to implement that in the package. Is there a design pattern for this?

  • I'm sure a class factory function would work, but
  • maybe some abstract base class (ABC) related tricks would solve it in an elegant way,
  • or perhaps some clever code in the __new__ function?


from How to add a base class automatically?

No comments:

Post a Comment