3

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?

Alice
  • 588
  • 1
  • 8
  • 25

2 Answers2

12

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()
    
matino
  • 17,199
  • 8
  • 49
  • 58
  • 1
    Also, what do you mean by _The problem with dictionaries is that you don't know which keys to expect_ ? – Alice Jan 12 '17 at 12:22
  • 1
    I mean that with the dictionary you don't declare the structure. Sure you create it somewhere but it can mutate in another place of your code. – matino Jan 12 '17 at 12:24
  • VS Code is capable of suggesting the keys for a dictionary – netotz Oct 02 '21 at 18:38
3

Looking in the docs, namedtuples appear 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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555