You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It doesn't appear that there is a cpformat-like function to format a colored string (with ansi styles, etc.). I wouldn't mind much if it weren't for the fact that user-defined classes show up as default object stubs (e.g. <SomeClass object>) and the __repr__ magic method only supports returning strings.
This makes it nearly impossible to have a nicely formatted class instance when consumed by prettyprinter.
The text was updated successfully, but these errors were encountered:
Until this shows up in the API, you can easily create your own cpformat() function by wrapping cpprint(), redirecting it's stream output to a StringIO stream to capture it, and then returning the text as a string.
It turns out that prettyprinter's own pformat() is essentially implemented the same way internally.
Put the code below into a cprettyprinter.py file:
"""Colorized prettyprinter formatImplements cpformat() to return a colorized pretty printed formatted string.As of 0.17.0 the prettyprinter library does not yet implement a cpformat() function."""fromprettyprinterimportcpprintfromioimportStringIOdefcpformat(object, **kwargs):
"""Return a pretty printed colorized representation of the object as a str. Args: object: The object to format. Any other keyword arguments supported by prettyprinter's cpprint() function. Returns: A colorized representation of the object as a str. """output=StringIO()
cpprint(object, stream=output, **kwargs)
returnoutput.getvalue()
And use it like this:
Added bonus:
I always use the colorama library to create colored text in Python. For some reason (which I haven't gotten to the bottom of) if you init colorama with colorama.init(autoreset=True) it modifies your stdout in a way that inhibits prettyprinter's cpprint() from working (i.e. the output renders uncolored). But printing the output of cpformat() (e.g. print(cpformat(my_object)) ) successfully renders in color even when colorama's autoreset is enabled.
Description
It doesn't appear that there is a
cpformat
-like function to format a colored string (with ansi styles, etc.). I wouldn't mind much if it weren't for the fact that user-defined classes show up as default object stubs (e.g.<SomeClass object>
) and the__repr__
magic method only supports returning strings.This makes it nearly impossible to have a nicely formatted class instance when consumed by prettyprinter.
The text was updated successfully, but these errors were encountered: