During my online class one of my python tutors told me that namedtuple
can cause more harm than good.
I am confused why. Can someone please specify when to use namedtuple
and when not to?
During my online class one of my python tutors told me that namedtuple
can cause more harm than good.
I am confused why. Can someone please specify when to use namedtuple
and when not to?
The classic example of namedtuple is something like this...
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(x=1, y=2)
>>> p.x
1
p.y
2
The thing I think most people find attractive at first is the ability to make a class so easily and be able to instanciate with keyword args Point(x=1, y=2)
and do dotted access like p.x
and p.y
.
However, there are a lot of things that are easily overlooked and is rather inflexible. Unexpected things can happen for subclasses, too. Unless namedtuple really hits your use-case, you're better off using SimpleNamespace
if you just want dotted-name lookups and a nice repr.
from types import SimpleNamespace
class Point(SimpleNameSpace):
def __init__(self, x, y=0):
# simple wrapper to accept arguments positionally or as keywords with defaults
super().__init__(x=x, y=y)
Few problem's what I can see is
You can't specify default arguments values for namedtuple classes.This makes them unwieldy when your data may have many optional properties .
The attribute values of namedtuple instances are still accessible using numerical indexes and iteration .Especially in externalised API's , this can lead to unintentional usage that makes it harder to move to real class later.If you are not in control of all of the usage of namedtuple instances , its' better define your own class
and for when to use it please do see the comment by IMCoins