• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: Create an Enum using a custom mix-in type

Resolved: Create an Enum using a custom mix-in type

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

In the relevant section of the Python Enum documentation, it is mentioned that mix-in types can be used to ensure items belong to that type and act as objects of that type, like in the example:
However, the documentation does not give any examples on how to use a custom class as a mix-in type, and I’ve failed miserably at that. Is it even possible? And if so, how do I do it?
The code I’m trying to write is
I’ve already tried:
  • Defining another class, EnumFwfField, and using it as a mix-in, i.e.
    class EnumFwfField(FwfField, Enum):
        pass
    
    class CnefeSchema(EnumFwfField, Enum):
        ...
    
    but I get the same error as above;
  • Setting the Enum fields (in this example, state_code) to FwfField, i.e.
    class CnefeSchema(FwfField, Enum):
        state_code = FwfField("int", "Código da UF", 2)
        ...
    
    but then I get
    Traceback (most recent call last):
      File "src/conf/schemas.py", line 25, in <module>
        class CnefeSchema(EnumFwfField, Enum):
      File "/usr/lib/python3.10/enum.py", line 298, in __new__
        enum_member.__init__(*args)
    TypeError: FwfField.__init__() missing 2 required positional arguments: 'name' and 'width'
    

Answer:

The issue you are having is because in your above code you have a name attribute in your Field dataclass, but Enum will not let you set a name attribute.
Rename that field to something else, for example 'dname', and it should work.
(The error message in 3.11 is more informative.)

If you have better answer, please add a comment about this, thank you!

enums oop python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: linq2db throws exception when filtering by nested collection

02/04/2023

Resolved: Table data is coming as empty in React

02/04/2023

Resolved: In a Pinescript v5 Strategy why is my bool not working?

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.