0

Namedtuple is amaziing, but this question confusing me for a long time.

In the python docs namedtuple

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

It's Basic exmaple as

Point = namedtuple('Point', ['x', 'y'])
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

I think it's more facile and tuple-like to define a namedtuple as

Point = namedtuple(['x', 'y'])
EmployeeRecord = namedtuple('name, age, title, department, paygrade')

What's the reason that namedtuple should be implementd with a verbose typename?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 4
    Think about it. How would you're `namedtuple` class know what its name is suppose to be? – Christian Dean May 14 '18 at 23:49
  • 1
    https://docs.python.org/3/library/typing.html#typing.NamedTuple – Ry- May 14 '18 at 23:53
  • anonymous function could know its name by `name = lambda x:x*x` @ChristianDean – AbstProcDo May 15 '18 at 00:13
  • 2
    @Tool Then it's no longer an anonymous function, just bad practice. When you're naming lambdas, just write a function. Anyway, besides the point... – cs95 May 15 '18 at 00:16
  • So, I get the point, function can be implemented anonymously, while class cannot. @cᴏʟᴅsᴘᴇᴇᴅ – AbstProcDo May 15 '18 at 00:19
  • 1
    @Tool that lambda still doesn't have a distinctive `__name__` attribute because you aren't supposed to care about that. `func = lambda x:x; print(function.__name__)` will give you `''`. However, with a namedtuple you get a nice `__repr__` like `Point(x=0, y=0)`, which is a lot nicer than some canned `(x=0,y=0)` – juanpa.arrivillaga May 15 '18 at 00:45
  • 1
    And you *could* have an anonymous type, or at least, a type whose name is an [empty string](https://stackoverflow.com/questions/1123000/does-python-have-anonymous-classes?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) but while anonymous functions are sometimes useful/expedient, anonymous types are not. And since Python doesn't force you to write a class definition for everything, there really is no need for anonymous classes. – juanpa.arrivillaga May 15 '18 at 00:49
  • 1
    Finally, remeber, `namedtuple` isn't returning *a namedtuple* it's returning a type/class, so it shouldn't resemble the `tuple` constructor – juanpa.arrivillaga May 15 '18 at 00:52

0 Answers0