Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding typing name twice when creating namedtuple

namedtuple creation often requires typing its name twice, once to provide the name of the module level variable containing the new class, and once to set the __name__ attribute of the new class (used for printing out the class objects, I think mostly for debugging, logging, etc.).

Is there any downside, besides being slightly unexpected, to using a function (new_namedtuple below) to reduce boilerplate code? And is using globals() correct or should it use exec? Of course, it would only work when we want the class name and the variable name to be the same:

>>> from collections import namedtuple
>>> def new_namedtuple(name, *args, **kwargs):
...   globals()[name] = namedtuple(name, *args, **kwargs)
...
>>> new_namedtuple('Point', 'x y')
>>> p = Point(x=1, y=10)
>>> p
Point(x=1, y=10)

Edit: @Moinuddin Quadri pointed out imports will fail. That's no good. So let me rephrase my question: what's the best way to do it? Or is it not worth it?

like image 215
max Avatar asked Sep 07 '25 18:09

max


1 Answers

The recommend way of using typing.NamedTuple in 3.6 will satisfy your request but requires you use type hinting.

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

p = Point(1, 10)

Typing hinting rubs some the wrong way. Unfortunately, collections.namedtuple doesn't support this useage, fingers crossed that changes.

like image 73
Guy Gangemi Avatar answered Sep 10 '25 01:09

Guy Gangemi