Support adding of representers for whole class-hierarchies.
See original GitHub issueI have a project which has a bunch of Enums and must dump them safely to send the output to an application written in another language. So an output like:
!!python/object/apply:__main__.Foo [1]
is not viable. And adding representers is not maintainable as the given class hierarchy is strongly subject to modification (new classes are tacked on regularly, all subclasses of Enum
). As it is now, I must register a new “representer” for each such class. As a contrived example:
from yaml import dump as dump_yaml, add_representer
from enum import Enum
class Foo(Enum):
A = 1
B = 2
class Bar(Enum):
A = 1
B = 2
def enum_representer(dumper, data):
return dumper.represent_scalar('!enum', str(data.value))
data = {
'value1': Foo.A,
'value2': Bar.B
}
add_representer(Foo, enum_representer)
add_representer(Bar, enum_representer)
print(dump_yaml(data))
As you can see in the last couple of lines, I need to register a representer for each subclass of Enum. What makes things work in my case, is that those enums come from an external library in my application. If that library decides to add a new subclass and an instance of that ends up in a data structure I wan to serialise, the application will create a non-safe dump.
It would be much nicer if I could simply register a representer for the base class Enum
.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:3
- Comments:7 (1 by maintainers)
Top GitHub Comments
Works for me!
Adding a multi_representer for
Enum
(or some intermediate subclass) to a Dumper is the way the original API intends for this to work. Directly overridingrepresent_data
on a custom dumper works too, but kinda sidesteps the designed mechanism.Closing this, since there are several ways to handle this with the existing API.