2

I recently visited a forum with python tricks and came across this:

>>> Points = type("Points", (object,), {'x' : None, 'y' : None})
>>> Player = Points()
>>> Player.x = 23
>>> Player.y = 54
>>> Player.x
23
>>> Player.y - Player.x
31
...

This syntax reminds me of the named tuples syntax:

>>> from collections import namedtuple
>>> Points = namedtuple("Points", ['x', 'y'])
>>> Player = Points(
    x = 23,
    y = 54
)
>>> Player.x
23
>>> Player.y - Player.x
21
...

And I can't understand how they differ except that named tuples can't be changed and have indexing. What advantages have named tuples and type function and what is better to use in our projects?

JuSt HumAn
  • 21
  • 1
  • 1
    `type` is the base metaclass used to construct all types (classes) in Python. `namedtuple` is a function that returns types with very specific behavior. I'm sure it uses `type` internally to do what it does, but as a practical matter it is like a more limited version of `type` that only makes a certain kind of class. – kindall Jun 02 '19 at 15:06

1 Answers1

0

Let's dive into the source code!

First, we'll take a look at the definition of namedtuple:

result = type(typename, (tuple,), class_namespace)

class_namespace contains the field names:

    for index, name in enumerate(field_names):
        doc = _sys.intern(f'Alias for field number {index}')
        class_namespace[name] = _tuplegetter(index, doc)

namedtuple essentially creates an object, derived from tuple, wheres your first example creates an object from the base object.

Conclusion

You can check this answer to see the difference in memory between the two. It's up to you to decide which one to use, based on readability and other stuff you would like to use with that object. I would say that based on the answer above, looking at your example code, I would go with namedtuple (Or the typing version of it which is even cooler!:

class Employee(NamedTuple):
    name: str
    id: int

)

AdamGold
  • 4,941
  • 4
  • 29
  • 47