![Example](https://raw.githubusercontent.com/andy-landy/traceback_with_variables/master/header.png)
<h2 align="center">Python Traceback (Error Message) Printing Variables</h2>
<p align="center">Very simple to use, but versatile when needed. Try for debug and keep for production.</p>
<p align="center">
<a href="https://github.com/andy-landy/traceback_with_variables/actions"><img alt="Actions Status" src="https://github.com/andy-landy/traceback_with_variables/workflows/tests/badge.svg"></a>
<a href="https://github.com/andy-landy/traceback_with_variables/blob/master/.github/workflows/master-test.yml#L59"><img title="code tests coverage is 100%" alt="code tests coverage is 100%" src="https://img.shields.io/badge/coverage-100%25-brightgreen.svg"></a>
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/LICENSE"><img alt="License: MIT" src="https://img.shields.io/github/license/andy-landy/traceback_with_variables?color=informational"></a>
<a href="https://pepy.tech/project/traceback-with-variables"><img alt="Downloads" src="https://static.pepy.tech/badge/traceback-with-variables"></a>
<a href="https://pypi.org/project/traceback-with-variables"><img alt="PyPI" src="https://img.shields.io/pypi/v/traceback-with-variables"></a>
<a href="https://anaconda.org/conda-forge/traceback-with-variables"><img src="https://img.shields.io/conda/vn/conda-forge/traceback-with-variables"></a>
<a href="https://pypi.org/project/traceback-with-variables"><img alt="PyPI" src="https://img.shields.io/badge/python-3.6+-blue.svg"></a>
<a href="https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling"><img title="windows, mac, linux etc." alt="Platform" src="https://img.shields.io/badge/platform-all-blue.svg"></a>
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/override.py#L9"><img title="type hints everywhere" alt="Annotations coverage" src="https://img.shields.io/badge/type--hints-100%25-blueviolet.svg"></a>
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/override.py#L8"><img title="no obscure objects, only transparent functions and data classes" alt="No-OOP" src="https://img.shields.io/badge/no OOP-100%25-blueviolet.svg"></a>
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/setup.py"><img alt="Dependencies" src="https://img.shields.io/badge/dependencies-0-blueviolet.svg"></a>
<a href="https://colab.research.google.com/github/andy-landy/traceback_with_variables/blob/master/examples/colab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
<a href="https://gitter.im/andy-landy/traceback-with-variables"><img alt="Gitter" src="https://img.shields.io/gitter/room/andy-landy/traceback-with-variables?color=blueviolet"></a>
<!--
<a href="https://pypi.org/project/traceback-with-variables"><img alt="pip Downloads" src="https://static.pepy.tech/personalized-badge/traceback-with-variables?period=total&units=none&left_color=grey&right_color=orange&left_text=pip downloads"></a>
<a href="https://anaconda.org/conda-forge/traceback-with-variables/"><img alt="conda-forge Downloads" src="https://img.shields.io/conda/dn/conda-forge/traceback-with-variables?color=orange&label=conda%20downloads"></a>
-->
</p>
<br/>
> βIt is useless work that darkens the heart.β
> <em>β Ursula K. Le Guin</em>
Tired of useless job of putting all your variables into debug exception messages? Just stop it.
Automate it and clean your code. Once and for all.
---
_Contents:_ **[Installation](#installation)** | **[π Quick Start](#-quick-start)**
| **[Colors](#colors)**
| **[How does it save my time?](#how-does-it-save-my-time)** |
**[Examples and recipes](#examples-and-recipes)** | **[Reference](#reference)**
| **[FAQ](#faq)**
---
> :warning: **I'm open to update this module to meet new use cases and to make using it easier and fun**: so any proposal or advice or warning is very welcome and will be taken into account of course. When I started it I wanted to make a tool meeting all standard use cases. I think in this particular domain this is rather achievable, so I'll try. Note `next_version` branch also. Have fun!
---
### Installation
```
pip install traceback-with-variables==2.1.1
```
```
conda install -c conda-forge traceback-with-variables
```
to use shorter `tb` alias in interactive mode call this once:
```
python3 -c 'from traceback_with_variables.tb_alias import create_tb_alias as c; c()'
```
### π Quick Start
Using without code editing, <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/external_script.sh">running your script/command/module</a>:
```
traceback-with-variables tested_script.py ...srcipt's args...
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/simple.py">Simplest usage</a>, for the whole program:
```python
from traceback_with_variables import activate_by_import
```
or just (if you added an alias by the above command)
```python
import tb.a
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_function.py">Decorator</a>, for a single function:
```python
@prints_exc
# def main(): or def some_func(...):
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_code_block.py">Context</a>, for a single code block:
```python
with printing_exc():
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/work_with_traceback_lines.py">Work with traceback lines</a> in a custom manner:
```python
lines = list(iter_exc_lines(e))
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_cur_tb.py">No exception but you want to print the stack anyway?</a>:
```python
print_cur_tb()
```
Using a logger [<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_function.py">with a decorator</a>, <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_code_block.py">with a context</a>]:
```python
with printing_exc(file_=LoggerAsFile(logger)):
# or
@prints_exc(file_=LoggerAsFile(logger)):
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_traceback.py">Print traceback</a> in interactive mode after an exception:
```
>>> print_exc()
```
<a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/format_customized.py">Customize</a> any of the previous examples:
```python
fmt.max_value_str_len = 10000
fmt.skip_files_except = 'my_project'
```
### Colors
![Example](https://raw.githubusercontent.com/andy-landy/traceback_with_variables/master/color_schemes.png)
### How does it save my time?
* Turn a code totally covered by debug formatting from this:
```diff
def main():
sizes_str = sys.argv[1]
h1, w1, h2, w2 = map(int, sizes_str.split())
- try:
return get_avg_ratio([h1, w1], [h2, w2])
- except:
- logger.error(f'something happened :(, variables = {locals()[:1000]}')
- raise
- # or
- raise MyToolException(f'something happened :(, variables = {locals()[:1000]}')
def get_avg_ratio(size1, size2):
- try:
return mean(get_ratio(h, w) for h, w in [size1, size2])
- except:
- logger.error(f'something happened :(, size1 = {size1}, size2 = {size2}')
- raise
- # or
- raise MyToolException(f'something happened :(, size1 = {size1}, size2 = {size2}')
def get_ratio(height, width):
- try:
return height / width
- except:
- logger.error(f'something happened :(, width = {width}, height = {height}')
- raise
- # or
- raise MyToolException(f'something happened :(, width = {width}, height = {height}')
```
into this (zero debug code):
```diff
+ from traceback_with_variables import activate_by_import
def main():
sizes_str = sys.argv[1]
h1, w1, h2, w2 = map(int, sizes_str.split())
return get_avg_ratio([h1, w1], [h2, w2])
def get_avg_ratio(size1, size2):
return mean(get_ratio(h, w) for h, w in [size1, size2])
def get_ratio(height, width):
return height / width
```
And obtain total debug info spending 0 lines of code:
```
Traceback with variables (most recent call last):
File "./temp.py", line 7, in main
return get_avg_ratio([h1, w1], [h2, w2])
sizes_str = '300 200 300 0'
h1 = 300
w1 = 200
h2 = 300
w2 = 0
File "./temp.py", line 10, in get_avg_ratio
return mean([get_ratio(h, w) for h, w in [size1, size2]])
size1 = [300, 200]
size2 = [300, 0]
File "./temp.py", line 10, in <listcomp>
return mean([get_ratio(h, w) for h, w in [size1, size2]])
.0 = <tuple_iterator object at 0x7ff61e35b820>
h = 300
w = 0
File "./temp.py", line 13, in get_ratio
return height / width
height = 300
width = 0
builtins.ZeroDivisionError: division by zero
```
* Automate your logging too:
```python
logger = logging.getLogger('main')
def main():
...
with printing_exc(file_=LoggerAsFile(logger))
...
```
```
2020-03-30 18:24:31 main ERROR Traceback with variables (most recent call last):
2020-03-30 18:24:31 main ERROR File "./temp.py", line 7, in main
2020-03-30 18:24:31 main ERROR return get_avg_ratio([h1, w1], [h2, w2])
2020-03-30 18:24:31 main ERROR sizes_str = '300 200 300 0'
2020-03-30 18:24:31 main ERROR h1 = 300
2020-03-30 18:24:31 main ERROR w1 = 200
2020-03-30 18:24:31 main ERROR h2 = 300
2020-03-30 18:24:31 main ERROR w2 = 0
2020-03-30 18:24:31 main ERROR File "./temp.py", line 10, in get_avg_ratio
2020-03-30 18:24:31 main ERROR return mean([get_ratio(h, w) for h, w in [size1, size2]])
2020-03-30 18:24:31 main ERROR size1 = [300, 200]
2020-03-30 18:24:31 main ERROR size2 = [300, 0]
2020-03-30 18:24:31 main ERROR File "./temp.py", line 10, in <listcomp>
2020-03-30 18:24:31 main ERROR return mean([get_ratio(h, w) for h, w in [size1, size2]])
2020-03-30 18:24:31 main ERROR .0 = <tuple_iterator object at 0x7ff412acb820>
2020-03-30 18:24:31 main ERROR h = 300
2020-03-30 18:24:31 main ERROR w = 0
2020-03-30 18:24:31 main ERROR File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR return height / width
2020-03-30 18:24:31 main ERROR height = 300
2020-03-30 18:24:31 main ERROR width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
```
* Free your exceptions of unnecessary information load:
```python
def make_a_cake(sugar, eggs, milk, flour, salt, water):
is_sweet = sugar > salt
is_vegan = not (eggs or milk)
is_huge = (sugar + eggs + milk + flour + salt + water > 10000)
if not (is_sweet or is_vegan or is_huge):
raise ValueError('This is unacceptable, look why!')
...
```
* β Should I use it after debugging is over, i.e. *in production*?
Yes, of course! That way it might save you even more time (watch out for sensitive data
like passwords and tokens in you logs, use skip_files_except to hide code from libs AND custom_var_printers to hide own locals). Note: you can deploy more serious frameworks, e.g. `Sentry`
<br/>
* Stop this tedious practice in production:
step 1: Notice some exception in a production service. \
step 2: Add more printouts, logging, and exception messages. \
step 3: Rerun the service. \
step 4: Wait till (hopefully) the bug repeats. \
step 5: Examine the printouts and possibly add some more info (then go back to step 2). \
step 6: Erase all recently added printouts, logging and exception messages. \
step 7: Go back to step 1 once bugs appear.
### Examples and recipes
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/external_script.sh">run python code without changes: a script, a module, a commnad</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/simple.py">simple usage</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/simple_jupyter.py">simple usage in Jupyter or IPython</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_cur_tb.py">print current stack, when there's no exception</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/interactive_print_last_exception.py">print last exception in Python console</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/change_global_printer.py">manually change global printer</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/change_global_printer_in_jupyter.py">manually change global printer in Jupyter or IPython</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_function.py">working with a function</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_function.py">working with a function, logging</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_code_block.py">working with a code block</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_code_block.py">working with a code block, logging</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/work_with_traceback_lines.py">get traceback lines for custom things</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/flask.py">using with `flask`</a>
* <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/examples/format_customized.py">customize the output</a>
### Reference
#### All functions have `fmt=` argument, a `Format` object with fields:
* `max_value_str_len` max length of each variable string, -1 to disable, default=1000
* `objects_details` depth of details of objects inspection
* `ellipsis_rel_pos` when truncating long strings where to put the "...", from 0.0 to 1.0, default=0.7
* `max_exc_str_len` max length of exception, should variable print fail, -1 to disable, default=10000
* `before` number of code lines before the raising line, default=0
* `after` number of code lines after the raising line, default=0
* `ellipsis_` string to denote long strings truncation, default=`...`
* `skip_files_except` use to print only certain files; list of regexes, ignored if empty, default=None
* `brief_files_except` use to print variables only in certain files; list of regexes, ignored if empty, default=None
* `custom_var_printers` list of pairs of (filter, printer); filter is a name fragment, a type or a function or a list thereof; printer returns `None` to skip a var
* `color_scheme` is `None` or one of <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/color.py">`ColorSchemes`</a>: `.none` , `.common`, `.nice`, `.synthwave`. `None` is for auto-detect
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/activate_by_import.py">`activate_by_import`</a>
Just import it. No arguments, for real quick use in regular Python.
```python
from traceback_with_variables import activate_by_import
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/activate_in_ipython_by_import.py">`activate_in_ipython_by_import`</a>
Just import it. No arguments, for real quick use in Jupyter or IPython.
```python
from traceback_with_variables import activate_in_ipython_by_import
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/global_hooks.py">`global_print_exc`</a>
Call once in the beginning of your program, to change how traceback after an uncaught exception looks.
```python
def main():
override_print_exc(...)
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/global_hooks.py">`global_print_exc_in_ipython`</a>
Call once in the beginning of your program, to change how traceback after an uncaught exception looks.
```python
def main():
override_print_exc(...)
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py">`print_exc`</a>
Prints traceback for a given/current/last (first being not `None` in the priority list) exception to a file, default=`sys.stderr`. Convenient for manual console or Jupyter sessions or custom try/except blocks. Note that it can be called with a given exception value or it can auto discover current exception in an `except:` block or it can auto descover last exception value (long) after `try/catch` block.
```python
print_exc()
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py">`print_cur_tb`</a>
Prints current traceback when no exception is raised.
```python
print_cur_tb()
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py">`prints_exc`</a>
Function decorator, used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the function call. Program exiting due to unhandled exception still prints a usual traceback.
```python
@prints_exc
def f(...):
@prints_exc(...)
def f(...):
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py">`printing_exc`</a>
Context manager (i.e. `with ...`), used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the `with` scope. Program exiting due to unhandled exception still prints a usual traceback.
```python
with printing_exc(...):
```
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py">`LoggerAsFile`</a>
A logger-to-file wrapper, to pass a logger to print tools as a file.
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py">`iter_exc_lines`</a>
Iterates the lines, which are usually printed one-by-one in terminal.
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py">`format_exc`</a>
Like `iter_exc_lines` but returns a single string.
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py">`iter_cur_tb_lines`</a>
Like `iter_exc_lines` but doesn't need an exception and prints upper frames..
---
#### <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py">`format_cur_tb`</a>
Like `iter_cur_tb_lines` but returns a single string.
---
### FAQ
* In Windows console crash messages have no colors.
The default Windows console/terminal cannot print [so called *ansi*] colors, but this is
<a href="https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling">fixable</a>
, especially with modern Windows versions. Therefore colors are disabled by default,
but you can enable them and check if it works in your case.
You can force enable colors by passing `--color-scheme common` (for complete list of colors pass `--help`) console argument.
* Windows console prints junk symbols when colors are enabled.
The default Windows console/terminal cannot print [so called *ansi*] colors, but this is
<a href="https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling">fixable</a>
, especially with modern Windows versions. If for some reason the colors are wrongly enabled by default,
you can force disable colors by passing `--color-scheme none` console argument.
* Bash tools like grep sometimes fail to digest the output when used with pipes (`|`) because of colors.
Please disable colors by passing `--color-scheme none` console argument.
The choice for keeping colors in piped output was made to allow convenient usage of `head`, `tail`, file redirection etc.
In cases like `| grep` it might have issues, in which case you can disable colors.
* Output redirected to a file in `> output.txt` manner has no colors when I `cat` it.
This is considered a rare use case, so colors are disabled by default when outputting to a file.
But you can force enable colors by passing `--color-scheme common` (for complete list of colors pass `--help`) console argument.
* `activate_by_import` or `global_print_exc` don't work in Jupyter or IPython as if not called at all.
In Jupyter or IPython you should use `activate_in_ipython_by_import` or `global_print_exc_in_ipython`. IPython handles exceptions differently than regular Python.
* The server framework (`flask`, `streamlit` etc.) still shows usual tracebacks.
In such frameworks tracebacks are printed not while exiting the program (the program continues running), hence you should override exception handling in a manner
proper for the given framework. Please address the `flask` example.
* How do I reduce output? I don't need all files or all variables.
Use `skip_files_except`, `brief_files_except`, `custom_var_printers` to cut excess output.
* I have ideas about good colors.
Please fork, add a new `ColorScheme` to <a href="https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/color.py">`ColorSchemes`</a>
and create a Pull Request to `next_version` branch. <a href="https://en.wikipedia.org/wiki/ANSI_escape_code">Choose the color codes</a> and visually
test it like `python3 -m traceback_with_variables.main --color-scheme {its name} examples/for_readme_image.py`.
* My code doesn't work.
Please <a href="https://gitter.im/andy-landy/traceback-with-variables">post your case</a>. You are very welcome!
* Other questions or requests to elaborate answers.
Please <a href="https://gitter.im/andy-landy/traceback-with-variables">post your question or request</a>. You are very welcome!
Raw data
{
"_id": null,
"home_page": "https://github.com/andy-landy/traceback_with_variables",
"name": "traceback-with-variables",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.6",
"maintainer_email": null,
"keywords": "python, traceback, locals, logging, debugging, print, variables, python3, stacktrace, arguments, errors, error-handling, dump, exception-handling, exceptions, pretty, pretty-print, frame, simple, colors, jupyter, jupyter-notebook, ipython, customize",
"author": "Andrey Lyashko",
"author_email": "andydashlandy@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/1f/17/f791c416d550b53b50cd5cc1e7da9522f95aca79df03c41f2fc8427c0879/traceback-with-variables-2.1.1.tar.gz",
"platform": null,
"description": "![Example](https://raw.githubusercontent.com/andy-landy/traceback_with_variables/master/header.png)\n\n<h2 align=\"center\">Python Traceback (Error Message) Printing Variables</h2>\n<p align=\"center\">Very simple to use, but versatile when needed. Try for debug and keep for production.</p>\n\n<p align=\"center\">\n<a href=\"https://github.com/andy-landy/traceback_with_variables/actions\"><img alt=\"Actions Status\" src=\"https://github.com/andy-landy/traceback_with_variables/workflows/tests/badge.svg\"></a>\n<a href=\"https://github.com/andy-landy/traceback_with_variables/blob/master/.github/workflows/master-test.yml#L59\"><img title=\"code tests coverage is 100%\" alt=\"code tests coverage is 100%\" src=\"https://img.shields.io/badge/coverage-100%25-brightgreen.svg\"></a>\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/LICENSE\"><img alt=\"License: MIT\" src=\"https://img.shields.io/github/license/andy-landy/traceback_with_variables?color=informational\"></a>\n<a href=\"https://pepy.tech/project/traceback-with-variables\"><img alt=\"Downloads\" src=\"https://static.pepy.tech/badge/traceback-with-variables\"></a>\n<a href=\"https://pypi.org/project/traceback-with-variables\"><img alt=\"PyPI\" src=\"https://img.shields.io/pypi/v/traceback-with-variables\"></a>\n<a href=\"https://anaconda.org/conda-forge/traceback-with-variables\"><img src=\"https://img.shields.io/conda/vn/conda-forge/traceback-with-variables\"></a>\n<a href=\"https://pypi.org/project/traceback-with-variables\"><img alt=\"PyPI\" src=\"https://img.shields.io/badge/python-3.6+-blue.svg\"></a>\n<a href=\"https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling\"><img title=\"windows, mac, linux etc.\" alt=\"Platform\" src=\"https://img.shields.io/badge/platform-all-blue.svg\"></a>\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/override.py#L9\"><img title=\"type hints everywhere\" alt=\"Annotations coverage\" src=\"https://img.shields.io/badge/type--hints-100%25-blueviolet.svg\"></a>\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/override.py#L8\"><img title=\"no obscure objects, only transparent functions and data classes\" alt=\"No-OOP\" src=\"https://img.shields.io/badge/no OOP-100%25-blueviolet.svg\"></a>\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/setup.py\"><img alt=\"Dependencies\" src=\"https://img.shields.io/badge/dependencies-0-blueviolet.svg\"></a>\n<a href=\"https://colab.research.google.com/github/andy-landy/traceback_with_variables/blob/master/examples/colab.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n<a href=\"https://gitter.im/andy-landy/traceback-with-variables\"><img alt=\"Gitter\" src=\"https://img.shields.io/gitter/room/andy-landy/traceback-with-variables?color=blueviolet\"></a>\n<!--\n<a href=\"https://pypi.org/project/traceback-with-variables\"><img alt=\"pip Downloads\" src=\"https://static.pepy.tech/personalized-badge/traceback-with-variables?period=total&units=none&left_color=grey&right_color=orange&left_text=pip downloads\"></a>\n<a href=\"https://anaconda.org/conda-forge/traceback-with-variables/\"><img alt=\"conda-forge Downloads\" src=\"https://img.shields.io/conda/dn/conda-forge/traceback-with-variables?color=orange&label=conda%20downloads\"></a>\n-->\n</p>\n<br/>\n\n> \u201cIt is useless work that darkens the heart.\u201d \n> <em>\u2013 Ursula K. Le Guin</em>\n\nTired of useless job of putting all your variables into debug exception messages? Just stop it. \nAutomate it and clean your code. Once and for all.\n\n---\n\n_Contents:_ **[Installation](#installation)** | **[\ud83d\ude80 Quick Start](#-quick-start)**\n| **[Colors](#colors)**\n| **[How does it save my time?](#how-does-it-save-my-time)** | \n**[Examples and recipes](#examples-and-recipes)** | **[Reference](#reference)**\n| **[FAQ](#faq)**\n\n---\n\n> :warning: **I'm open to update this module to meet new use cases and to make using it easier and fun**: so any proposal or advice or warning is very welcome and will be taken into account of course. When I started it I wanted to make a tool meeting all standard use cases. I think in this particular domain this is rather achievable, so I'll try. Note `next_version` branch also. Have fun!\n\n---\n\n### Installation\n\n```\npip install traceback-with-variables==2.1.1\n```\n```\nconda install -c conda-forge traceback-with-variables\n```\n\nto use shorter `tb` alias in interactive mode call this once:\n```\npython3 -c 'from traceback_with_variables.tb_alias import create_tb_alias as c; c()'\n```\n\n### \ud83d\ude80 Quick Start\n\nUsing without code editing, <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/external_script.sh\">running your script/command/module</a>:\n```\ntraceback-with-variables tested_script.py ...srcipt's args...\n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/simple.py\">Simplest usage</a>, for the whole program:\n```python\n from traceback_with_variables import activate_by_import\n```\nor just (if you added an alias by the above command)\n```python\n import tb.a\n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_function.py\">Decorator</a>, for a single function:\n```python\n @prints_exc\n # def main(): or def some_func(...):\n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_code_block.py\">Context</a>, for a single code block:\n```python\n with printing_exc():\n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/work_with_traceback_lines.py\">Work with traceback lines</a> in a custom manner:\n```python\n lines = list(iter_exc_lines(e))\n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_cur_tb.py\">No exception but you want to print the stack anyway?</a>:\n```python\n print_cur_tb()\n```\n\nUsing a logger [<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_function.py\">with a decorator</a>, <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_code_block.py\">with a context</a>]:\n```python\n with printing_exc(file_=LoggerAsFile(logger)):\n # or\n @prints_exc(file_=LoggerAsFile(logger)): \n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_traceback.py\">Print traceback</a> in interactive mode after an exception:\n```\n >>> print_exc()\n```\n\n<a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/format_customized.py\">Customize</a> any of the previous examples:\n```python\n fmt.max_value_str_len = 10000\n fmt.skip_files_except = 'my_project'\n```\n\n\n### Colors\n\n![Example](https://raw.githubusercontent.com/andy-landy/traceback_with_variables/master/color_schemes.png)\n\n\n### How does it save my time?\n\n* Turn a code totally covered by debug formatting from this:\n\n ```diff\n def main():\n sizes_str = sys.argv[1]\n h1, w1, h2, w2 = map(int, sizes_str.split())\n - try:\n return get_avg_ratio([h1, w1], [h2, w2])\n - except:\n - logger.error(f'something happened :(, variables = {locals()[:1000]}')\n - raise\n - # or\n - raise MyToolException(f'something happened :(, variables = {locals()[:1000]}')\n\n def get_avg_ratio(size1, size2):\n - try:\n return mean(get_ratio(h, w) for h, w in [size1, size2])\n - except:\n - logger.error(f'something happened :(, size1 = {size1}, size2 = {size2}')\n - raise\n - # or\n - raise MyToolException(f'something happened :(, size1 = {size1}, size2 = {size2}')\n\n def get_ratio(height, width):\n - try:\n return height / width\n - except:\n - logger.error(f'something happened :(, width = {width}, height = {height}')\n - raise\n - # or\n - raise MyToolException(f'something happened :(, width = {width}, height = {height}')\n ```\n into this (zero debug code):\n\n ```diff\n + from traceback_with_variables import activate_by_import\n\n def main():\n sizes_str = sys.argv[1]\n h1, w1, h2, w2 = map(int, sizes_str.split())\n return get_avg_ratio([h1, w1], [h2, w2])\n\n def get_avg_ratio(size1, size2):\n return mean(get_ratio(h, w) for h, w in [size1, size2])\n\n def get_ratio(height, width):\n return height / width\n ```\n\n And obtain total debug info spending 0 lines of code:\n\n ```\n Traceback with variables (most recent call last):\n File \"./temp.py\", line 7, in main\n return get_avg_ratio([h1, w1], [h2, w2])\n sizes_str = '300 200 300 0'\n h1 = 300\n w1 = 200\n h2 = 300\n w2 = 0\n File \"./temp.py\", line 10, in get_avg_ratio\n return mean([get_ratio(h, w) for h, w in [size1, size2]])\n size1 = [300, 200]\n size2 = [300, 0]\n File \"./temp.py\", line 10, in <listcomp>\n return mean([get_ratio(h, w) for h, w in [size1, size2]])\n .0 = <tuple_iterator object at 0x7ff61e35b820>\n h = 300\n w = 0\n File \"./temp.py\", line 13, in get_ratio\n return height / width\n height = 300\n width = 0\n builtins.ZeroDivisionError: division by zero\n ```\n\n* Automate your logging too:\n\n ```python\n logger = logging.getLogger('main')\n\n def main():\n ...\n with printing_exc(file_=LoggerAsFile(logger))\n ...\n ```\n\n ```\n 2020-03-30 18:24:31 main ERROR Traceback with variables (most recent call last):\n 2020-03-30 18:24:31 main ERROR File \"./temp.py\", line 7, in main\n 2020-03-30 18:24:31 main ERROR return get_avg_ratio([h1, w1], [h2, w2])\n 2020-03-30 18:24:31 main ERROR sizes_str = '300 200 300 0'\n 2020-03-30 18:24:31 main ERROR h1 = 300\n 2020-03-30 18:24:31 main ERROR w1 = 200\n 2020-03-30 18:24:31 main ERROR h2 = 300\n 2020-03-30 18:24:31 main ERROR w2 = 0\n 2020-03-30 18:24:31 main ERROR File \"./temp.py\", line 10, in get_avg_ratio\n 2020-03-30 18:24:31 main ERROR return mean([get_ratio(h, w) for h, w in [size1, size2]])\n 2020-03-30 18:24:31 main ERROR size1 = [300, 200]\n 2020-03-30 18:24:31 main ERROR size2 = [300, 0]\n 2020-03-30 18:24:31 main ERROR File \"./temp.py\", line 10, in <listcomp>\n 2020-03-30 18:24:31 main ERROR return mean([get_ratio(h, w) for h, w in [size1, size2]])\n 2020-03-30 18:24:31 main ERROR .0 = <tuple_iterator object at 0x7ff412acb820>\n 2020-03-30 18:24:31 main ERROR h = 300\n 2020-03-30 18:24:31 main ERROR w = 0\n 2020-03-30 18:24:31 main ERROR File \"./temp.py\", line 13, in get_ratio\n 2020-03-30 18:24:31 main ERROR return height / width\n 2020-03-30 18:24:31 main ERROR height = 300\n 2020-03-30 18:24:31 main ERROR width = 0\n 2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero\n ```\n\n* Free your exceptions of unnecessary information load:\n\n ```python\n def make_a_cake(sugar, eggs, milk, flour, salt, water):\n is_sweet = sugar > salt\n is_vegan = not (eggs or milk)\n is_huge = (sugar + eggs + milk + flour + salt + water > 10000)\n if not (is_sweet or is_vegan or is_huge):\n raise ValueError('This is unacceptable, look why!')\n ...\n ```\n\n* \u2014 Should I use it after debugging is over, i.e. *in production*?\n\n Yes, of course! That way it might save you even more time (watch out for sensitive data\n like passwords and tokens in you logs, use skip_files_except to hide code from libs AND custom_var_printers to hide own locals). Note: you can deploy more serious frameworks, e.g. `Sentry`\n\n<br/>\n\n* Stop this tedious practice in production:\n\n step 1: Notice some exception in a production service. \\\n step 2: Add more printouts, logging, and exception messages. \\\n step 3: Rerun the service. \\\n step 4: Wait till (hopefully) the bug repeats. \\\n step 5: Examine the printouts and possibly add some more info (then go back to step 2). \\\n step 6: Erase all recently added printouts, logging and exception messages. \\\n step 7: Go back to step 1 once bugs appear.\n\n\n### Examples and recipes\n\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/external_script.sh\">run python code without changes: a script, a module, a commnad</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/simple.py\">simple usage</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/simple_jupyter.py\">simple usage in Jupyter or IPython</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_cur_tb.py\">print current stack, when there's no exception</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/interactive_print_last_exception.py\">print last exception in Python console</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/change_global_printer.py\">manually change global printer</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/change_global_printer_in_jupyter.py\">manually change global printer in Jupyter or IPython</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_function.py\">working with a function</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_function.py\">working with a function, logging</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/print_for_code_block.py\">working with a code block</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/log_for_code_block.py\">working with a code block, logging</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/work_with_traceback_lines.py\">get traceback lines for custom things</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/flask.py\">using with `flask`</a>\n* <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/examples/format_customized.py\">customize the output</a>\n\n### Reference\n\n#### All functions have `fmt=` argument, a `Format` object with fields:\n* `max_value_str_len` max length of each variable string, -1 to disable, default=1000\n* `objects_details` depth of details of objects inspection\n* `ellipsis_rel_pos` when truncating long strings where to put the \"...\", from 0.0 to 1.0, default=0.7\n* `max_exc_str_len` max length of exception, should variable print fail, -1 to disable, default=10000\n* `before` number of code lines before the raising line, default=0\n* `after` number of code lines after the raising line, default=0\n* `ellipsis_` string to denote long strings truncation, default=`...`\n* `skip_files_except` use to print only certain files; list of regexes, ignored if empty, default=None\n* `brief_files_except` use to print variables only in certain files; list of regexes, ignored if empty, default=None\n* `custom_var_printers` list of pairs of (filter, printer); filter is a name fragment, a type or a function or a list thereof; printer returns `None` to skip a var\n* `color_scheme` is `None` or one of <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/color.py\">`ColorSchemes`</a>: `.none` , `.common`, `.nice`, `.synthwave`. `None` is for auto-detect \n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/activate_by_import.py\">`activate_by_import`</a>\nJust import it. No arguments, for real quick use in regular Python.\n```python\nfrom traceback_with_variables import activate_by_import\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/activate_in_ipython_by_import.py\">`activate_in_ipython_by_import`</a>\nJust import it. No arguments, for real quick use in Jupyter or IPython.\n```python\nfrom traceback_with_variables import activate_in_ipython_by_import\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/global_hooks.py\">`global_print_exc`</a>\nCall once in the beginning of your program, to change how traceback after an uncaught exception looks.\n```python\ndef main():\n override_print_exc(...)\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/global_hooks.py\">`global_print_exc_in_ipython`</a>\nCall once in the beginning of your program, to change how traceback after an uncaught exception looks.\n```python\ndef main():\n override_print_exc(...)\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py\">`print_exc`</a>\nPrints traceback for a given/current/last (first being not `None` in the priority list) exception to a file, default=`sys.stderr`. Convenient for manual console or Jupyter sessions or custom try/except blocks. Note that it can be called with a given exception value or it can auto discover current exception in an `except:` block or it can auto descover last exception value (long) after `try/catch` block.\n```python\nprint_exc()\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py\">`print_cur_tb`</a>\nPrints current traceback when no exception is raised.\n```python\nprint_cur_tb()\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py\">`prints_exc`</a>\nFunction decorator, used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the function call. Program exiting due to unhandled exception still prints a usual traceback.\n```python\n@prints_exc\ndef f(...):\n\n@prints_exc(...)\ndef f(...):\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py\">`printing_exc`</a>\nContext manager (i.e. `with ...`), used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the `with` scope. Program exiting due to unhandled exception still prints a usual traceback.\n```python\nwith printing_exc(...):\n```\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/print.py\">`LoggerAsFile`</a>\nA logger-to-file wrapper, to pass a logger to print tools as a file.\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py\">`iter_exc_lines`</a>\nIterates the lines, which are usually printed one-by-one in terminal.\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py\">`format_exc`</a>\nLike `iter_exc_lines` but returns a single string.\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py\">`iter_cur_tb_lines`</a>\nLike `iter_exc_lines` but doesn't need an exception and prints upper frames..\n\n---\n\n#### <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/core.py\">`format_cur_tb`</a>\nLike `iter_cur_tb_lines` but returns a single string.\n\n---\n\n### FAQ\n\n* In Windows console crash messages have no colors. \n\n The default Windows console/terminal cannot print [so called *ansi*] colors, but this is \n <a href=\"https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling\">fixable</a>\n , especially with modern Windows versions. Therefore colors are disabled by default,\n but you can enable them and check if it works in your case.\n You can force enable colors by passing `--color-scheme common` (for complete list of colors pass `--help`) console argument.\n\n* Windows console prints junk symbols when colors are enabled.\n\n The default Windows console/terminal cannot print [so called *ansi*] colors, but this is \n <a href=\"https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling\">fixable</a>\n , especially with modern Windows versions. If for some reason the colors are wrongly enabled by default,\n you can force disable colors by passing `--color-scheme none` console argument.\n\n* Bash tools like grep sometimes fail to digest the output when used with pipes (`|`) because of colors.\n\n Please disable colors by passing `--color-scheme none` console argument.\n The choice for keeping colors in piped output was made to allow convenient usage of `head`, `tail`, file redirection etc.\n In cases like `| grep` it might have issues, in which case you can disable colors.\n\n* Output redirected to a file in `> output.txt` manner has no colors when I `cat` it.\n\n This is considered a rare use case, so colors are disabled by default when outputting to a file.\n But you can force enable colors by passing `--color-scheme common` (for complete list of colors pass `--help`) console argument.\n\n* `activate_by_import` or `global_print_exc` don't work in Jupyter or IPython as if not called at all.\n\n In Jupyter or IPython you should use `activate_in_ipython_by_import` or `global_print_exc_in_ipython`. IPython handles exceptions differently than regular Python. \n\n* The server framework (`flask`, `streamlit` etc.) still shows usual tracebacks.\n\n In such frameworks tracebacks are printed not while exiting the program (the program continues running), hence you should override exception handling in a manner\n proper for the given framework. Please address the `flask` example.\n\n* How do I reduce output? I don't need all files or all variables.\n\n Use `skip_files_except`, `brief_files_except`, `custom_var_printers` to cut excess output.\n\n* I have ideas about good colors.\n\n Please fork, add a new `ColorScheme` to <a href=\"https://github.com/andy-landy/traceback_with_variables/tree/master/traceback_with_variables/color.py\">`ColorSchemes`</a>\n and create a Pull Request to `next_version` branch. <a href=\"https://en.wikipedia.org/wiki/ANSI_escape_code\">Choose the color codes</a> and visually\n test it like `python3 -m traceback_with_variables.main --color-scheme {its name} examples/for_readme_image.py`. \n\n* My code doesn't work. \n\n Please <a href=\"https://gitter.im/andy-landy/traceback-with-variables\">post your case</a>. You are very welcome!\n\n* Other questions or requests to elaborate answers.\n\n Please <a href=\"https://gitter.im/andy-landy/traceback-with-variables\">post your question or request</a>. You are very welcome!\n\n\n",
"bugtrack_url": null,
"license": null,
"summary": "Adds variables to python traceback. Simple, lightweight, controllable. Debug reasons of exceptions by logging or pretty printing colorful variable contexts for each frame in a stacktrace, showing every value. Dump locals environments after errors to console, files, and loggers. Works with Jupyter and IPython.",
"version": "2.1.1",
"project_urls": {
"Homepage": "https://github.com/andy-landy/traceback_with_variables"
},
"split_keywords": [
"python",
" traceback",
" locals",
" logging",
" debugging",
" print",
" variables",
" python3",
" stacktrace",
" arguments",
" errors",
" error-handling",
" dump",
" exception-handling",
" exceptions",
" pretty",
" pretty-print",
" frame",
" simple",
" colors",
" jupyter",
" jupyter-notebook",
" ipython",
" customize"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "280e8c0ad75b348e1f9db2a2f3b327624214e9b2cf4ac9a8976734867aeedd1e",
"md5": "459dee2a42bfbc70aa4bbd42e900d8e5",
"sha256": "a98566d3931d151f43b1307e228b13fff5022a5c67defc3f53dbde64e8128e0b"
},
"downloads": -1,
"filename": "traceback_with_variables-2.1.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "459dee2a42bfbc70aa4bbd42e900d8e5",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.6",
"size": 19607,
"upload_time": "2024-11-19T01:09:00",
"upload_time_iso_8601": "2024-11-19T01:09:00.871579Z",
"url": "https://files.pythonhosted.org/packages/28/0e/8c0ad75b348e1f9db2a2f3b327624214e9b2cf4ac9a8976734867aeedd1e/traceback_with_variables-2.1.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "1f17f791c416d550b53b50cd5cc1e7da9522f95aca79df03c41f2fc8427c0879",
"md5": "6327812d06d99650c69466f3aad646e1",
"sha256": "ca1ab9cd2871c3be3bbc57bb7b2dfe4b427763f81da6c632663d27231eaab132"
},
"downloads": -1,
"filename": "traceback-with-variables-2.1.1.tar.gz",
"has_sig": false,
"md5_digest": "6327812d06d99650c69466f3aad646e1",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6",
"size": 23364,
"upload_time": "2024-11-19T01:09:02",
"upload_time_iso_8601": "2024-11-19T01:09:02.239070Z",
"url": "https://files.pythonhosted.org/packages/1f/17/f791c416d550b53b50cd5cc1e7da9522f95aca79df03c41f2fc8427c0879/traceback-with-variables-2.1.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-19 01:09:02",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "andy-landy",
"github_project": "traceback_with_variables",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "traceback-with-variables"
}