0

When making my tkinter app project, sometimes I need to quickly know the current values of the variables I made, for debugging purposes, so I make a line like this:

root.bind("< F1>", lambda e: print(f"var1: {var1} \n var2: {var2} \n [etc]"))

which basically prints out the values of the variables I specifically list in, when I press F1. The problem with this is that manually typing each variable is a pain when you have a lot, so surely there is a smarter and automatic way of doing this. I'm guessing maybe there is a dictionary like "globals()" excluding the built-ins (meaning only the variables made by the user)? If there isn't such a thing, can someone give me an alternative? Thanks

  • 1
    *can someone give me an alternative?* - use an actual debugger. https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues lists many of them (if you read more posts, not just the top-voted one). Spyder is one which seems to be missing there. – tevemadar Apr 09 '22 at 13:07

2 Answers2

1

Other than globals() there is locals() but I don't think that's what you want. You can filter the globals that start with two underscores though:

>>> var = 1
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'var': 1}
>>> dict(filter(lambda i: not i[0].startswith("__"), globals().items()))
{'var': 1}
>>> 

If this isn't what you want, you should define "only the variables made by the user" more clearly.

Ekrem Dinçel
  • 1,053
  • 6
  • 17
0

Ekrem's answer is good enough for most cases, but it will also conflict with any imported modules, etc. There is simply no way of knowing what is user-made and what is imported, but you can filter globals to remove functions, classes, modules, and other items that are clearly not user-defined variables. However, if you have any lines like from module import some_constant, then it's nearly impossible to clearly categorize it as user-defined without explicitly marking a variable as user-defined (by adding it to a list or dictionary).

Epic Programmer
  • 383
  • 3
  • 12