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
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GW5ZPEET5V26XE3VBSJBOFEU7CAPO6TD/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to