Created
September 12, 2008 16:24
-
-
Save jeremyBanks/10472 to your computer and use it in GitHub Desktop.
[2010-01] getting names of variable at run-time in python
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
#!/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