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?
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.
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.
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.
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.
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, useint.__new__()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With