Closed ahopkins closed 5 years ago
I thought this was a bug, but in fact it isn't. The problem is that, with the mro
, type(Status)
returns RandomMetaclass
instead of EnumMeta
(of course). To make it work, you simply need to add your type
(after declaring it and before instantiating with middle.Model
) in middle's TypeRegistry
:
from enum import Enum
from enum import EnumMeta
from enum import auto
import random
import middle
from middle import TypeRegistry
class RandomMetaclass(EnumMeta):
@property
def RANDOM(self):
member_map = [x for x in self._member_map_.values()]
return random.choice(member_map)
class BaseEnum(Enum, metaclass=RandomMetaclass):
pass
class Status(BaseEnum):
DRAFT = auto()
PROPOSED = auto()
ACCEPTED = auto()
REJECTED = auto()
ABANDONED = auto()
TypeRegistry[RandomMetaclass] = EnumMeta
class Item(middle.Model):
title: str
status: Status
item = Item(title="FooBar", status=Status.RANDOM)
print(item)
I know, this is not far from perfect - I can see if I can find a __base__
attribute inside the given type (RandomMetaclass.__base__ == enum.EnumMeta
), but I don't know if it's good to go that far (into guessing the type). Ideas?
Nice. Thanks for the heads up. That seems a pretty simple solution to an outlier of a use case.
Description
I tried to implement
middle
with anEnum
that usesEnumMeta
to implement a custommetaclass
.What I Did
Snippets
Here is the code that produced the exception.
I confirmed that it works if I do not use
EnumMeta
.The snippet provided (if any) can be used to create unit tests for this issue.