hauntsaninja / pyp

Easily run Python at the shell! Magical, but never mysterious.
MIT License
1.41k stars 39 forks source link

Allow user to override pypprint #31

Open soraxas opened 2 years ago

soraxas commented 2 years ago

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

soraxas commented 6 months ago

Any new updates?