pyyaml icon indicating copy to clipboard operation
pyyaml copied to clipboard

safe_dump for decimals?

Open benwhalley opened this issue 6 years ago • 3 comments

I was having problem with tablib exports which depends on pyyml. I wonder, is this expected behaviour?

import yaml
from decimal import *
yaml.dump(Decimal(2.1))

works, but produces this:

"!!python/object/apply:decimal.Decimal ['2.100000000000000088817841970012523233890533447265625']\n"

And using safe_dump:

yaml.safe_dump(Decimal(2.1))

Produced the following error:

RepresenterError: cannot represent an object: 2.100000000000000088817841970012523233890533447265625

benwhalley avatar Feb 20 '19 21:02 benwhalley

@benwhalley PyYAML is treating this as a generic class instance, and safe_dump does not handle those.

Looks like a custom representer needs to be added. See https://github.com/yaml/pyyaml/blob/master/lib/yaml/representer.py#L269 for float representer.

Would be happy to consider a PR for this.

ingydotnet avatar Feb 28 '19 01:02 ingydotnet

I have tried my hand at a PR here: #372

syre avatar Jan 15 '20 08:01 syre

Hello, this is still a problem in current version of yaml, why are we not allowed to save decimal numbers using safe_dump?

ghost avatar Oct 19 '21 08:10 ghost