Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format color (instead of simply print colored to stream) #69

Open
Qix- opened this issue Sep 11, 2019 · 1 comment
Open

Format color (instead of simply print colored to stream) #69

Qix- opened this issue Sep 11, 2019 · 1 comment

Comments

@Qix-
Copy link

Qix- commented Sep 11, 2019

  • PrettyPrinter version: 0.18.0
  • Python version: 3.7.4
  • Operating System: MacOS

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.

@epmoyer
Copy link

epmoyer commented Jan 7, 2021

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 format

Implements cpformat() to return a colorized pretty printed formatted string.
As of 0.17.0 the prettyprinter library does not yet implement a cpformat() function.
"""
from prettyprinter import cpprint
from io import StringIO


def cpformat(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)
    return output.getvalue()

And use it like this:
Screen Shot 2021-01-07 at 8 31 03 AM

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants