gaogaotiantian / objprint

A library that can print Python objects in human readable format
Apache License 2.0
519 stars 43 forks source link

Detect command environment #89

Closed happytree718 closed 1 year ago

happytree718 commented 1 year ago

Related Issues

This PR attempts to resolve issue #73.

Description

This PR updates the behavior of the op() function based on the environment in which it is called.

In the case of a REPL environment, the op() function will always return None. This makes calling chains impossible, but it is the best that can be done given that Source.executing(frame).node cannot return a valid node in a REPL environment.

In other environments, such as Jupyter Notebook and scripts, the op() function will check whether it is called directly to decide whether it should return None or the objects. The following are examples of different return values:

op(a)    # return None
op(op(a))  # outer op() returns None, inner op() returns object
b = op(a)  # return objects

This change helps prevent printing twice in the Jupyter Notebook case.

In the case where op() is disabled, it will just return the object, regardless of the environment.

Changes Made

Add a new function named return_object(), which checks the frame op() is called to decide whether this call should return objects or None. Created unit tests to verify the new behavior of the op() function

Testing

For the unittest section, since I don't know how to perfectly simulate the REPL and Jupyter Notebook environments, console and exec() are used as replacements. I am open to opinions on how to make the tests closer to real-world scenarios.

happytree718 commented 1 year ago

Required changes are addressed in the latest commit.