Can I get the local variables of a Python function from which an exception was thrown?

后端 未结 6 773
时光说笑
时光说笑 2020-12-08 00:54

I\'m writing a custom logging system for a project. If a function throws an exception, I want to log its local variables. Is it possible to access the raising function\'s

6条回答
  •  旧巷少年郎
    2020-12-08 01:29

    Useful for "handling" exceptions without using raise Exception(some_def_var) and also without using a library such as "inspect", for example.

    However, I think if is to handle the exception "in real", might be better to use something like raise Exception(some_def_var). See @capfredf answer.

    class MyClass():
    
        def __init__(self):
            self.my_attr_I = ""
            self.my_attr_II = ""
    
        def my_def_I(self):
            try:
                self.my_def_II()
            except Exception as e:
                print(self.my_attr_I)
                print(self.my_attr_II)
    
        def my_def_II(self):
            self.my_attr_I = "TO EXCEPT I"
            self.my_attr_II = "TO except II"
    
            # NOTE: We will treat it as a general exception! By Questor
            zero_division = 1/0
    

提交回复
热议问题