Skip to content

Instantly share code, notes, and snippets.

@jeremyBanks
Created September 12, 2008 16:24
Show Gist options
  • Save jeremyBanks/10472 to your computer and use it in GitHub Desktop.
Save jeremyBanks/10472 to your computer and use it in GitHub Desktop.
[2010-01] getting names of variable at run-time in python
#!/usr/bin/env python
# encoding: utf-8
from __future__ import division, with_statement
import sys
# Demonstrating a crude method of determining a variable's names/labels.
def main():
def getVariableNames(variable, globals, locals):
variables = {}
variables.update(globals)
variables.update(locals)
return [key for key, value in variables.items() if value is variable]
foo = "Example"
bar = foo
baz = "Woo"
print getVariableNames(bar, globals(), locals()) # prints ['bar', 'foo']
print getVariableNames(baz, globals(), locals()) # prints ['baz']
if __name__ == "__main__": main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment