Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namedtuple vs Dictionary

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?

like image 656
Alice Avatar asked Dec 08 '22 19:12

Alice


2 Answers

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()
    
like image 102
matino Avatar answered Jan 06 '23 13:01

matino


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.

like image 20
Willem Van Onsem Avatar answered Jan 06 '23 13:01

Willem Van Onsem