SuperCiocia
SuperCiocia

Reputation: 1971

When and why is a type object better than a dict?

I am adapting some code provided by a company (for controlling an instrument). I am not a python expert myself so I would like to understand if there is any particular advantage of doing something one way or the other.

Their code is basically

def enum(**enums):
    return type('Enum', (), enums)

Inst = enum(
    CONTINUE = 0,
    STOP = 1,
    LOOP = 2,
    END_LOOP = 3,
    JSR = 4,
    RTS = 5,
    BRANCH = 6,
    LONG_DELAY = 7,
    WAIT = 8,
    RTI = 9
)

and they use it to access the values of the above "entries" like:

Inst.RTS
% 5

From my understanding, Inst is a type object.


For the purposes of storing strings and their associated values, I could also define a dict:

Inst = {'CONTINUE':0, 'STOP':1, 'LOOP':2, 'END_LOOP':3, 'JSR':4, 'RTS':5}

and then basically getting the same result:

Inst['RTS']
% 5

Question

What is the use / what are the advantages of a type object over a normal dict? Or is the above example just a bad example?

Upvotes: 3

Views: 463

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 50076

Using the three-argument form of type is similar to defining a class:

class type(name, bases, dict)

With three arguments, return a new type object. This is essentially a dynamic form of the class statement.

Your Inst expression is a needlessly convoluted but practically equivalent way to explicitly define this class:

class Enum:
    CONTINUE = 0
    STOP = 1
    LOOP = 2
    END_LOOP = 3
    JSR = 4
    RTS = 5
    BRANCH = 6
    LONG_DELAY = 7
    WAIT = 8
    RTI = 9

Inst = Enum

The advantage of a class is that attributes are well-defined by the class. For example, you can use it to type-hint, type-check or reference the exact enum set. In contrast, a dict only has some keys and some values -- the exact members are coincidental.


Note that Python has the enum module since Python 3.4. It allows to define proper enums that replicate the features known from enums in other languages:

from enum import Enum, auto

class Inst(int, Enum):
    CONTINUE = auto()
    STOP = auto()
    LOOP = auto()
    END_LOOP = auto()
    JSR = auto()
    RTS = auto()
    BRANCH = auto()
    LONG_DELAY = auto()
    WAIT = auto()
    RTI = auto()

Upvotes: 5

blhsing
blhsing

Reputation: 106523

With:

def enum(**enums):
    return type('Enum', (), enums)

You are actually creating a class with the value of the argument enums as the __dict__ attribute, which is a dict itself, so it is not technically any "better" than a dict, but its usage is syntactically simpler than a dict, since:

Inst.RTS

is arguably cleaner to read and easier to type than

Inst['RTS']

Upvotes: 5

Related Questions