Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
flashburn Avatar asked Dec 09 '16 01:12

flashburn


People also ask

What is Auto () in Python?

auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.

How do you declare an enum in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.

Should enums be capitalized Python?

Notice that enumerations are not normal Python classes, even though they are defined in a similar way. As enumerations are meant to represent constant values, it is advisable to uppercase the enum member names.

How do you print an enum in Python?

The __str__() method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object. Now you can get the value of the enum directly, without accessing the value attribute on the enum member. You can also use square brackets to access enum members.


1 Answers

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__()

like image 66
MSeifert Avatar answered Oct 23 '22 06:10

MSeifert