Mapping integers with data types?

Viewed 29

I'm working on something that reads data from binary files. Data formats are often stored as integers that correspond to different types, and I typically interpret them by putting the possible types into tuples and indexing into them. Imagine A, B, and C are classes:

types = (A, B, C)
val = 0 # this would be read from the file
dataType = types[val]

Recently, I saw something that looked like a cleaner alternative to this online, but I can't remember anything specific about it and I haven't been able to find it again. This seems fine to me, but now I'm curious, is there a better way out there?

1 Answers

You might be thinking of enums, which can be accessed through the enum module.

python docs for enum

>>> import enum
>>> class Types(enum.Enum):
...     A = 1
...     B = 2
...     C = 3
...
>>> Types(1)
<Types.A: 1>
>>> Types(2)
<Types.B: 2>
>>> Types.B
<Types.B: 2>
>>> Types.C
<Types.C: 3>

You might also be thinking of a namedtuple from the collections module

python docs for named tuple

>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)  
>>> p[0] + p[1]    
33
>>> x, y = p     
>>> x, y
(11, 22)
>>> p.x + p.y    
33
>>> p            
Point(x=11, y=22)

There are countless ways to represent data though and it really comes down to the project you are working on and what makes the most sense in your current situation.

Related