An idea to allow implicit return of NamedTuples

I think this is the answer to “I’ve got a function that returns a dataclass. How do I treat it as a tuple?”. That is, you can’t modify the function to return a tuple or namedtuple.

Maybe use a decorator?

   @asnamedtuple("x y z")  
   def f(......) -> tuple[int, int, int]:
       ..........
       return x, y, z

It wasn’t a false memory! I just thought it was a dataclass method for some reason and not at the module level.

You want indexing for the ability of tuple unpacking.

__getitem__ is not necessary for unpacking.

For example, sets are unpackable, despite not supporting __getitem__.
>>> a, b = {1, 2}; a; b
1
2
>>> a, b = {1, 2}[0], {1, 2}[1]
<stdin>:1: SyntaxWarning: 'set' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable

What matters is whether the object is iterable.

Named tuples require an explicit creation of a class and a direct instantiation of it. To me, the proposed syntax seems like something that would only fit named tuples were they defined as a protocol where you don’t have to directly instantiate them (like TypedDict).

If we go from a precedent already in the language, args and kwargs (or rather the * and ** in the parameter definition of a function) we see that args becomes is a tuple and kwargs is a dict.

Therefor multiple named returns should actually become a dict if it should align with how the language handles the parameters of the function.

I am not arguing for or against this idea, I just want to point out what would align with in my opinion closest existing behaviour.

1 Like

If you’re new to python and see the syntax

def f(x1, x2):
  return y1=x1, y2=x2

I’d wager that you would assume it to be an implicit dict rather than the infinitely less common NamedTuple construct. It would take quite a while before most people understood what it did (hell, most people don’t know about NamedTuples currently), adding to the fact that I don’t really think it would be used very often. I also think NamedTuple needs to stay a bit niche to keep new people from finding out about it before they fully grasp the differences between dicts and normal tuples. This would add a lot of confusion to that learning process were it to become widespread syntax.

3 Likes

I would not feel comfortable with a namedtuple display syntax as long as namedtuple is a library type and not built into the language. Generally I don’t like the idea of a language’s syntax having a dependency on its standard library.

4 Likes

I’d prefer we be explicit here. If we decide to do something like this, why should it be a namedtuple, and not a dataclass, or a SimpleNamespace, or a TypeDict, or something else?

If someone wants a namedtuple… use namedtuples.

3 Likes