Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a key/value pair from yaml dump, in Python?

Suppose I have a naive class definition:

import yaml
class A:
    def __init__(self):
        self.abc = 1
        self.hidden = 100
        self.xyz = 2

    def __repr__(self):
        return yaml.dump(self)

A()

printing

!!python/object:__main__.A
abc: 1
hidden: 100
xyz: 2

Is there a clean way to remove a line containing hidden: 100 from yaml dump's printed output? The key name hidden is known in advance, but its numeric value may change.

Desired output:

!!python/object:__main__.A
abc: 1
xyz: 2

FYI: This dump is for display only and will not be loaded.

I suppose one can suppress key/value pair with key=hidden with use of yaml.representative. Another way is find hidden: [number] with RegEx in a string output.

like image 655
Oleg Melnikov Avatar asked Nov 29 '15 15:11

Oleg Melnikov


1 Answers

I looked at the documentation for pyyaml and did not find a way to achieve your objective. A work-around would be to delete the attribte hidden, call yaml.dump, then add it back in:

    def __repr__(self):
        hidden = self.hidden
        del self.hidden

        return yaml.dump(self)

        self.hidden = hidden

Taking a step back, why do you want to use yaml for __repr__? Can you just roll your own instead of relying on yaml?

like image 113
Hai Vu Avatar answered Oct 01 '22 06:10

Hai Vu