Python Inventory Management

So I’m practically brand new to Python (I have only written 1 randomizer code). I am trying to write a python version the 90’s classic, “Oregon Trail.” However, I need to make an inventory system where I can add and remove items. Can anyone help me do that?

That’s a vague question…

Are you having issues choosing the right data structure to represent your inventory in memory?

Maybe some tips here:


In retrospect the first link does not exactly apply to Python, but the questions you should ask yourself are already there. One good reference is also this decision diagram (also not for Python but for STL/C++), to start asking yourself good questions. Once you have thought about it a bit more, let us know what your answers are to those questions and we can probably help you move forward.

Doing this entirely in memory:

If this inventory is like adventure game inventories (you are carrying
an axe, a wand of healing, etc etc) then I would just use a Python
set(). It has handy .add and .remove methods.


inventory = set()




You should make yourself a class to represent inventory items (a) so
that they can have some common attibutes such as descriptions, types (eg
“axe”, so that your report can say “2 axes” by counting the types) etc
and (b) so that you can ensure they are suitable for use in a set.

For objects to be useable in a set Python needs (a) to be able to
compare them for equality, where “equality” means “is already present”
and (b) be able to hash equal items to the same hash value (because sets
are built like dicts, which use a hash table for fast access).

With an inventory, no item should be equal to another, otherwise adding
another axe would leave you with just one axe, since the set thinks it
already has an axe (equality).

When I do this I define a class like this:

class InventoryIteem:

    def __eq__(self, other):
        return self is other

    def __hash__(self):
        return id(self)

This ensures that only a specific item is equal to itself so that adding
your grandfather’s axe twice results in that specific axe being present
just one, but adding another axe adds an additional axe - it is a
different object and so not equal.

The hash function can be just id(self) - the unique per object id value
every object has - you’re just ensuring that adding the same object
hashes the same way.

If you need to persist this stuff (quit the programme and have the same
inventory when you restart), that is a separate problem: solve the
in-memory inventory first with a set. Later, tackle writing that to a
file and reading it back.

Cameron Simpson

This is exactly what I was looking for! Thanks a Ton.