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

Add option to change print function #145

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions devtools/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
MYPY = False
if MYPY:
from types import FrameType
from typing import Any, Generator, List, Optional, Union
from typing import Any, Callable, Generator, List, Optional, Union

pformat = PrettyFormat(
indent_step=int(os.getenv('PY_DEVTOOLS_INDENT', 4)),
Expand Down Expand Up @@ -108,9 +108,16 @@ def __repr__(self) -> StrType:
class Debug:
output_class = DebugOutput

def __init__(self, *, warnings: 'Optional[bool]' = None, highlight: 'Optional[bool]' = None):
def __init__(
self,
*,
warnings: 'Optional[bool]' = None,
highlight: 'Optional[bool]' = None,
logger_function: 'Optional[Callable[[str], None]]' = None,

Choose a reason for hiding this comment

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

If logger_function would have the same signature as print, you could initialize it to print per default.
That way you can get rid of the conditional code in __call__. One might have to wrap a logger into a lambda to ignore the additonal file/flush arguments.

):
self._show_warnings = env_bool(warnings, 'PY_DEVTOOLS_WARNINGS', True)
self._highlight = highlight
self._logger_function = logger_function

def __call__(
self,
Expand All @@ -122,7 +129,10 @@ def __call__(
) -> 'Any':
d_out = self._process(args, kwargs, frame_depth_)
s = d_out.str(use_highlight(self._highlight, file_))
print(s, file=file_, flush=flush_)
if self._logger_function:
self._logger_function(s)
else:
print(s, file=file_, flush=flush_)
if kwargs:
return (*args, kwargs)
elif len(args) == 1:
Expand Down