On Thu, Feb 18, 2021 at 11:50:17AM +1300, Greg Ewing wrote:
It's dead simple to define your own blank-object class, and you get to give it a name that reflects what you're really doing with it. I don't understand why there's such a fascination with things like SimpleNamespace.
Right, it takes only two lines of code. So let's do it! >>> class Thing: ... pass ... >>> obj = Thing(attr='value') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Thing() takes no arguments Hmmm. Okay, *three* lines of code: >>> class Thing: ... def __init__(self, **kw): ... vars(self).update(kw) ... >>> obj = Thing(attr='value') >>> print(obj) <__main__.Thing object at 0x7f2b07c23b80> Damn, that's about as useful as a screen door on a submarine. Let's give it a repr, so when debugging we can see what it actually is. So *five* lines of code: >>> class Thing: ... def __init__(self, **kw): ... vars(self).update(kw) ... def __repr__(self): ... return f'Thing({vars(self)})' ... >>> obj = Thing(attr='value') >>> print(obj) Thing({'attr': 'value'}) >>> obj == Thing(attr='value') False Bugger. So **ten** lines of code: >>> class Thing: ... def __init__(self, **kw): ... vars(self).update(kw) ... def __repr__(self): ... return f'Thing({vars(self)})' ... def __eq__(self, other): ... if isinstance(other, Thing): ... return vars(self) == vars(other) ... else: ... return NotImplemented ... >>> obj = Thing(attr='value') >>> print(obj) Thing({'attr': 'value'}) >>> obj == Thing(attr='value') True So we've gone from a trivial two-liner that doesn't do what we need, to ten lines, without docs or tests. Or we could just use a one-liner: >>> from types import SimpleNamespace and get all of that for free. And if it were a builtin, it would be a zero-liner. -- Steve