Is there @namedtuple for Python?

NamedTupleTools.jl ’ s @namedtuple is really nice for wrapping function returns quickly. Is there a similar thing in Python that only need to type once of the value? I didn’ t find one with search.

Python does not have syntax-level macros, so what you are asking for is rather not possible without very significant abuse of the language. On the other hand, python is famous for very significant abuse of the language, so you might be able to build some very hacky solution. Good places to start looking are the AST module, import hooks, eval, and company.

If you can permit yourself to encapsulate your expression into a string, then things become much simpler, but you then need to make your own parser for the language and lose IDE support.


By default, you can construct a named tuple in julia by using the variable names as keys:

julia> a = 1; b = 2

julia> (; a, b)
(a = 1, b = 2)

julia> (; a, b, c = 3)
(a = 1, b = 2, c = 3)

Maybe you could use PythonCall and have Julia do the heavy lifting?

No you can’t do this.

The Pythonic way is to create a new named tuple type at the top level

from collections import namedtuple
Foo = namedtuple("Foo", "x y z")

and construct it when needed

Foo(1, 2, 3)

Well it’s possible, it just looks differently :wink: You can wrap the function’s return values by directly passing it to the namedtuple constructor (as shown by @cjdoris) with * (similar to Julia’s splat ...) .

>>> from collections import namedtuple
... Foo = namedtuple("Foo", "x y z")

>>> def foo():
...     return (1, 2, 3)

>>> Foo(*foo())
Foo(x=1, y=2, z=3)