Using python to dump hexadecimals into YAML

前端 未结 3 724
长发绾君心
长发绾君心 2021-01-15 04:31

Now I\'m dumping into a YAML document. It\'s working as it should for the most part. When I try to dump a hexadecimal such as \"0x2A\" it converts to 42. Isn\'t there any wa

3条回答
  •  走了就别回头了
    2021-01-15 05:20

    This should do it:

    >>> import yaml
    >>> class HexInt(int): pass
    ... 
    >>> def representer(dumper, data):
    ...     return yaml.ScalarNode('tag:yaml.org,2002:int', hex(data))
    ... 
    >>> yaml.add_representer(HexInt, representer)
    >>> yaml.dump({"n": HexInt(42)})
    '{n: 0x2a}\n'
    

提交回复
热议问题