Last active
May 18, 2024 10:23
-
-
Save jftuga/8c9a46c86b669338ba99fe07d65d4918 to your computer and use it in GitHub Desktop.
Dump all Python variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
r""" | |
dump-all-variables.py | |
-John Taylor | |
2024-05-16 | |
Dumps both global and local Python variables and their values | |
""" | |
import json | |
import re | |
ALPHA = "alpha" | |
ONE = 1 | |
valid = True | |
Pi = 3.1415926 | |
colors = ("red", "blue", "green") | |
letters = {"a": 1, "z": 26} | |
match_re = re.compile("test.*?result") | |
class foo: | |
def __init__(self): | |
pass | |
def bar(a): | |
global Z | |
Z = "zzz" | |
return a + a | |
def main(): | |
d = 5 + 3j | |
a = 1234567890 | |
E = 3.1415 | |
C = False | |
b = "xyz" | |
f = bar(a) | |
g = foo() | |
# output global variables skipping ones that start w/ dunder and also skipping: modules, functions and classes | |
print() | |
print( | |
json.dumps( | |
{ | |
_: globals()[_] | |
for _ in sorted(dict(globals()), key=str.casefold) | |
if _[:2] != "__" and not str(globals()[_]).startswith(("<module", "<function", "<class")) | |
}, | |
default=str, | |
indent=4, | |
) | |
) | |
# output all local variables (does not require the inspect or types modules) | |
print() | |
print(json.dumps({_: locals()[_] for _ in sorted(list(locals()), key=str.casefold)}, default=str, indent=4)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision 15 Expected Output