Skip to content

Conversation

soraxas
Copy link

@soraxas soraxas commented Sep 12, 2022

This PR allows user to define their own pypprint.

Example

I can define a custom config at $PYP_CONFIG_PATH as follows:

import numpy as np
import plotly.express as pe
import matplotlib.pyplot as plt


def pypprint(*args, **kwargs):  # type: ignore
    from typing import Iterable
    import sys

    if len(args) != 1:
        return print(*args, **kwargs)

    x = args[0]

    if "matplotlib" in sys.modules:
        import matplotlib.pyplot as plt

        if any(isinstance(_x, plt.Artist) for _x in x):
            return plt.show()

    if "plotly" in sys.modules:
        import plotly.graph_objects as go

        if isinstance(x, go.Figure):
            return x.show()

    if isinstance(x, dict):
        for k, v in x.items():
            return print(f"{k}:", v, **kwargs)
    elif isinstance(x, Iterable) and not isinstance(x, str):
        for i in x:
            print(i, **kwargs)
        return
    else:
        return print(x, **kwargs)

then, running

pyp 'plt.plot([0,1,1.5])'

automatically open the plot for you:)


*Note, the return statement simply allows me to short-circuit the flow; and the checking on sys.modules helps to avoid unnecessary import of modules if the modules is not already imported

Signed-off-by: Tin Lai <oscar@tinyiu.com>
Copy link
Owner

@hauntsaninja hauntsaninja left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a neat feature!

However, the rest of pyp config is able to recursively reference other definitions in config (e.g. imports or other functions), which pypprint defined in this way would not. I'll take a shot at implementing that + adding some tests when I get some time.

@soraxas
Copy link
Author

soraxas commented Apr 7, 2024

Any new updates?

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

Successfully merging this pull request may close these issues.

2 participants