-1

All, I have this request but first I will explain what I'm trying to achieve. I coded a python script with many global variables but also many methods defined inside different modules (.py files).

The script sometimes moves to a method and inside this method I call another method defined in another module. The script is quite complex.

Most of my code is inside Try/Except so that every time an exception is triggered my code runs a method called "check_issue()" in which I print to console the traceback and then I ask myself if there's any variable's value I want to double check. Now, I read many stackoverflow useful pages in which users show how to use/select globals(), locals() and eval() to see current global variables and local variables.

What I would specifically need though is the ability to input inside method "check_issue()" the name of a variable that may be defined not as global and not inside the method check_issue() either. Using classes is not a solution since I would need to change hundreds of lines of code.

These are the links I already read:

This is a sample code that doesn't work:

a =  4
b = "apple"

def func_a():
    c = "orange"
    ...
    check_issue()

def check_issue():
    print("Something went wrong")
    var_to_review = input("Input name of var you want to review")
    # I need to be able to enter "c" and print the its value "orange"
    print(func_a.locals()[var_to_review ]) # this doesn't work

Could somebody suggest how to fix it? Many thanks

Lycos IUT
  • 158
  • 7
Angelo
  • 1,594
  • 5
  • 17
  • 50

1 Answers1

1

When you call locals() inside check_issue(), you can only access to the locals of this function, which would be : ['var_to_review'].

You can add a parameter to the check_issue function and pass locals whenever you call it.

a =  4
b = "apple"

def func_a():
    c = "orange"
    check_issue(locals())

def check_issue(local_vars):
    print("Something went wrong")
    var_to_review = input("Input name of var you want to review")
    print(local_vars[var_to_review])
Lycos IUT
  • 158
  • 7
vishal
  • 1,081
  • 2
  • 10
  • 27
  • This is a first great step and I would want to thank you for the prompt answer. There's a problem though. The code above is a simplistic representation of the real script I have. Meaning, I could call check_issue() inside method func_a() and func_a() may have been called inside func_b() and func_b() may be coming from another method called func_c(). What would you suggest in that case? How could I check local variables inside func_a(), func_b() and func_c() from check_issue() ? Thanks – Angelo Aug 06 '18 at 14:49