tobgu / pyrsistent

Persistent/Immutable/Functional data structures for Python
MIT License
2.03k stars 146 forks source link

pformat on pyrsistent objects #70

Open jml opened 9 years ago

jml commented 9 years ago

It'd be great if pprint and pformat worked "properly" on pyrsistent objects. That is, if the output of pformat(some_pmap) were comparable to pformat(some_dict).

That is, the following Python code...

from pyrsistent import pmap
from pprint import pprint

some_dict = {'foo': 'reverse the earth', 'bar': 'on a train to bristol', 'baz': 'some rather long line'}

print '## normal dict'
pprint(some_dict)
print

print '## pmap'
pprint(pmap(some_dict))

... produces this output ...

## normal dict
{'bar': 'on a train to bristol',
 'baz': 'some rather long line',
 'foo': 'reverse the earth'}

## pmap
pmap({'baz': 'some rather long line', 'foo': 'reverse the earth', 'bar': 'on a train to bristol'})

Whereas it should produce:

## normal dict
{'bar': 'on a train to bristol',
 'baz': 'some rather long line',
 'foo': 'reverse the earth'}

## pmap
pmap({
  'baz': 'some rather long line', 
  'foo': 'reverse the earth', 
  'bar': 'on a train to bristol'})

... or something similar

(Related to #69, but this is a request for enhancement, rather than a defect report. Fixing this would probably also fix #69)

tobgu commented 9 years ago

I agree, would be nice! I'll look into it.

itamarst commented 8 years ago

This seems difficult: in Python 2.7 and 3.4 pprint basically hardcodes the stdlib data structures (with issubclass check). One could monkey-patch the stdlib, as proposed here (http://stackoverflow.com/a/15417704) but that seems not great.

tobgu commented 8 years ago

Yes, I read that SO post as well when looking at this issue the first time. If it is implemented through monkey patching (I have not found any good alternatives) that would probably be done through an explicit call to some function (eg. pyrsistent.enable_pprint()). I wouldn't want to mess with the stdlib functionality without making it very explicit.

jml commented 8 years ago

Python 3.5 appears to have a more extensible implementation of pprint (https://github.com/python/cpython/blob/master/Lib/pprint.py). I don't know if it works out of the box w/ pyrsistent (I guess it ought to if pyrsistent uses the collections abstract base classes?).

I think a good way to start would be to avoid the question of monkey-patching altogether by providing alternative functions that pretty-format and pretty-print regular Python objects and pyrsistent objects. If it turns out that they are useful, then monkey-patching can be implemented separately.