Skip to content

Instantly share code, notes, and snippets.

@jftuga
Last active May 18, 2024 10:23
Show Gist options
  • Save jftuga/8c9a46c86b669338ba99fe07d65d4918 to your computer and use it in GitHub Desktop.
Save jftuga/8c9a46c86b669338ba99fe07d65d4918 to your computer and use it in GitHub Desktop.
Dump all Python variables
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()
@jftuga
Copy link
Author

jftuga commented May 18, 2024

Revision 15 Expected Output

{
    "ALPHA": "alpha",
    "colors": [
        "red",
        "blue",
        "green"
    ],
    "letters": {
        "a": 1,
        "z": 26
    },
    "match_re": "re.compile('test.*?result')",
    "ONE": 1,
    "Pi": 3.1415926,
    "valid": true,
    "Z": "zzz"
}
{
    "a": 1234567890,
    "b": "xyz",
    "C": false,
    "d": "(5+3j)",
    "E": 3.1415,
    "f": 2469135780,
    "g": "<__main__.foo object at 0x1008ae840>"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment