[Python-ideas] Anonymous namedtuples

Paul Moore p.f.moore at gmail.com
Tue Apr 19 10:26:08 EDT 2016


On 19 April 2016 at 15:09, Joseph Martinot-Lagarde
<contrebasse at gmail.com> wrote:
>> That's entirely possible. For the situations where order is
>> insignificant and unpacking is unnecessary, a SimpleNamespace would be
>> perfect, if people knew about it. Probably not worth moving the actual
>> class, but a quick little docs link might help.
>>
> How big a problem would it be to actually move the class to collections ?
> For example at the top of the documentation there is a table with all the
> available container classes, having SimpleNamespace would be far more
> discoverable than a paragraph in namedtuple.

Not incredibly hard, in theory. However...

Move the definition:

    SimpleNamespace = type(sys.implementation)

to collections (but note that this isn't *really* the definition, the
actual definition is in C, in the sys module, and is unnamed - to that
extent types, which is for exposing names for types that otherwise
aren't given built in names, is actually the right place for this
definition!) Update the documentation. Update the tests
(test/test_types.py) - this probably involves *moving* those tests to
test_collections.py. Add a backward compatibility name in types. Add
some tests for that backward compatibility name.

Work out what to do about pickle compatibility:

>>> from pickle import dumps
>>> from types import SimpleNamespace
>>> dumps(SimpleNamespace(a=1))
b'\x80\x03ctypes\nSimpleNamespace\nq\x00)Rq\x01}q\x02X\x01\x00\x00\x00aq\x03K\x01sb.'

Note that the type name (types.SimpleNamespace) is embedded in the
pickle. How do we avoid breaking pickles?

That's probably far from everything - this was 5 minutes' quick
investigation, and I'm not very experienced at doing this type of
refactoring. I'm pretty sure I've missed some things.

> The class could still be importable from types.SimpleNamespace for backward
> compatibility.

Where it's defined matters in the pickle case - so it's not quite that simple.

> Sorry for my noob questions...

Not at all. It's precisely because it "seems simple" that the feedback
people get seems negative at times - I hope the above gives you a
better idea of what might be involved in such a seemingly simple
change. So thanks for asking, and giving me the opportunity to clarify
:-)

In summary: It's not likely to be worth the effort, even though it
looks simple at first glance.
Paul


More information about the Python-ideas mailing list