Consider a case, in which a class needs an attribute only in a very limited context. (For example, only during initialization, which is handled by a factory) I do not want to include such an attribute in the class, in order to keep it as simple as possible.
In the concrete example, I have a sorted list of tree nodes with given depth. Every node is direct child of the last node that has a smaller depth and comes before the child node itself. Once the tree is properly built and all parents contain links to their children, the depth is no longer required.
Here are the options I have considered in python:
- Just including the attribute in the class (ugly)
- Monkey patching the attribute in the factory method and removing it afterwards (uglier)
- Using the following dataclass in the factory method:
@dataclass
class NodeAndDepth:
depth: int
node: Node
- Using the following class, and than "casting" the objects into the simpler one:
class NodeWithDepth(Node):
def __init__(self, depth, ...):
...