[Python] I want to know the variables in the function when an error occurs!

Introduction

How do you guys debug? Is it common to use a debugger or something like Pdb?

Aside from that, when an error occurs, you want to see the local variables in the function for the time being. However, since it is a "local" variable, it cannot be seen from outside the function and eventually runs to print.

This time, I created a decorator, hoping that at least the variables at the time of the error could be output together.

What I made

def raise_locals(f):
    import sys, traceback
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            ext = traceback.StackSummary.extract(traceback.walk_tb(exc_traceback), capture_locals=True)
            locals_ = ext[-1].locals
            if locals_:
                print('{' + ', '.join([f"'{k}': {v}" for k, v in locals_.items()]) + '}')
            raise
    return wrapper

The structure is like picking up a local variable through traceback if you try to run it and an error occurs. Let's use it.

@raise_locals
def f(x):
    a = x
    b = 1 / a
    a = 1
    
f(0)

out


{'x': 0, 'a': 0}
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-137-16e1baa342f5> in <module>
      5     a = 1
      6 
----> 7 f(0)

<ipython-input-136-f595b8b52afb> in wrapper(*args, **kwargs)
      3     def wrapper(*args, **kwargs):
      4         try:
----> 5             f(*args, **kwargs)
      6         except Exception as e:
      7                 exc_type, exc_value, exc_traceback = sys.exc_info()

<ipython-input-137-16e1baa342f5> in f(x)
      2 def f(x):
      3     a = x
----> 4     b = 1 / a
      5     a = 1
      6 

ZeroDivisionError: division by zero

The local variable at the time of the error is displayed before the usual error statement.

def f(x):
    a = x
    b = 1 / a

@raise_locals
def main():
    f(x=0)

if __name__=='__main__':
    main()

If you attach it to the parent function, you can see the local variable of the function where the error occurred no matter where the error occurred.

Recommended Posts

[Python] I want to know the variables in the function when an error occurs!
[Linux] I want to know the date when the user logged in
I want to display the progress in Python!
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
Python Note: When you want to know the attributes of an object
I want to write in Python! (3) Utilize the mock
I want to use the R dataset in python
I want to do something in Python when I finish
[python] What to do when an error occurs in send_keys of headless chrome
I want to get the file name, line number, and function name in Python 3.4
I tried to implement the mail sending function in Python
I want to know the features of Python and pip
I want to replace the variables in the python template file and mass-produce it in another file.
I want to know the weather with LINE bot feat.Heroku + Python
How to know the internal structure of an object in Python
Check the argument type annotation when executing a function in Python and make an error
I got an AttributeError when mocking the open method in python
I want to run the Python GUI when starting Raspberry Pi
[Python] When you want to use all variables in another file
I want to know the population of each country in the world.
I got an error when I tried to process luigi in parallel on windows, but the solution
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
I want to color a part of an Excel string in Python
I want to leave an arbitrary command in the command history of Shell
Python: I want to measure the processing time of a function neatly
[OSX] [pyenv] What to do when an SSL error occurs in pip
I want to do Dunnett's test in Python
I want to create a window in Python
I want to merge nested dicts in Python
I implemented the inverse gamma function in python
Error when trying to install psycopg2 in Python
I want to use the activation function Mish
I want to improve efficiency with Python even in an experimental system (4) Use ser.close () when an error is thrown using try syntax
[Question] In sk-learn random forest regression, an error occurs when the number of parallels is set to -1.
I get an error when I put a Python plugin in Visual Studio Code under the pyenv environment
[Python] What to do if an error occurs in pip (pyinstaller, pyautogui, etc.)
In the Chainer tutorial, I get an error when importing a package. (mock)
I want to use Python in the environment of pyenv + pipenv on Windows 10
I stumbled on the character code when converting CSV to JSON in Python
I got an error when trying to run Hello World in Go language
I got an error when I put opencv in python3 with Raspberry Pi [Remedy]
I want to send Gmail with Python, but I can't because of an error
If an exception occurs in the function, it will be transmitted to the caller 2
I want to store the result of% time, %% time, etc. in an object (variable)
If an exception occurs in the function, it will be transmitted to the caller 1
I want to write in Python! (1) Code format check
I tried to graph the packages installed in Python
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I get an Import Error in Python Beautiful Soup
How to know the current directory in Python in Blender
I want to write in Python! (2) Let's write a test
Even in JavaScript, I want to see Python `range ()`!
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
I get an error when I put opencv in pyautoGUI
I want to work with a robot in python.
Specifies the function to execute when the python program ends
When you get an error in python scraping (requests)