flashburn
flashburn

Reputation: 4538

Fix 'new enumerations must be created as'

I'm working in Python 2 and have the following class

import enum

class MyClass(object):
    pass

@enum.unique
classMyEnum(enum.IntEnum, MyClass):
    A = 1
    B = 2

When I run this code I get a following error:

  File "C:\Python27\lib\site-packages\enum\__init__.py", line 506, in _get_mixins_
    raise TypeError("new enumerations must be created as "
TypeError: new enumerations must be created as `ClassName([mixin_type,] enum_type)`

I work with Python on a regular basis but I must admit I never really dove into it. I can't really figure out what is going on. I'm not really sure how to read this error. Can someone help me out with this?

Upvotes: 12

Views: 10489

Answers (1)

MSeifert
MSeifert

Reputation: 152820

The error is because you need to list the MixinType before your Enum class, like:

class FunEnum(int, Enum):
    A = 1
    B = 2

But since you're already using intEnum (which is already a mixed enum) you don't want mix in another type, right? So you can simply use:

@enum.unique
class FunEnum(enum.IntEnum):
    A = 1
    B = 2

The mixin type defines to which class the values are converted and how could Python resolve this if you want MyClass and int? Therefore attempthing it throws another error:

@enum.unique
class FunEnum(str, enum.IntEnum):
    A = 1
    B = 2

TypeError: multiple bases have instance lay-out conflict

or

class MyClass(object):
    pass

@enum.unique
class FunEnum(MyClass, enum.IntEnum):
    A = 1
    B = 2

TypeError: object.__new__(FunEnum) is not safe, use int.__new__()

Upvotes: 9

Related Questions