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

Allow user to override pypprint #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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

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.

None yet

2 participants