So I'm programming a game and I need a datatype that can store a multitude of variables ranging from lists, tuples, strings and integers. I'm torn between using either dictionaries or namedtuples.
GameData = namedtuple('GameData', ['Stats', 'Inventory', 'Name', 'Health'])
current_game = GameData((20,10,55,3), ['Sword', 'Apple', 'Potion'], 'Arthur', 100)
GameData = {'Stats': (20,10,55,3), 'Inventory': ['Sword', 'Apple', 'Potion'], 'Name': 'Arthur', 'Health': 100}
You see, the biggest problem here is all of these values may change, so I need a mutable datatype, which is not the namedtuple. Looking in the docs, namedtuples appear to have ._replace(), so does that make it mutable?
I also like how namedtuples have a __repr__ method that prints in the name=value format. Also, the functionality of assigning separate __doc__ fields to each value in the namedtuple is very useful. Is there this functionality with dictionaries?
Just use a class.
The problem with dictionaries is that you don't know which keys to expect and your IDE won't be able to autocomplete for you.
The problem with namedtuple is that is not mutable.
With a custom class you get both readable attributes, mutable objects and a lot of flexibility. Some alternatives to consider:
Starting from Python 3.7 you could use the dataclasses module:
from dataclasses import dataclass
@dataclass
class GameData:
stats: tuple
inventory: list
name: str
health: int
In case other Python versions, you could try attrs package:
import attr
@attr.s
class GameData:
stats = attr.ib()
inventory = attr.ib()
name = attr.ib()
health = attr.ib()
Looking in the docs,
namedtuplesappear to have._replace(), so does that make it mutable?
No, as specified in the documentation, it creates a new namedtuple, with the value replaced.
If you want the data to be mutable, you better construct a class yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With