Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Ogreman
Created April 23, 2014 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ogreman/11218810 to your computer and use it in GitHub Desktop.
Save Ogreman/11218810 to your computer and use it in GitHub Desktop.
import itertools
def name_func(var, scope=globals):
try:
return itertools.ifilter(
lambda x: var is scope().get(x),
scope().keys()
).next()
except StopIteration:
return None
class NamedVar(type):
def __new__(meta, name, bases, dct):
dct['__varname__'] = property(name_func)
return type.__new__(meta, name, bases, dct)
class A(object):
__metaclass__ = NamedVar
def __init__(self, v=0):
self._val = v
def __repr__(self):
return '{var}: {val}'.format(
var=self.__varname__,
val=self._val
)
if __name__ == '__main__':
a = A()
b = A(1)
c = A(1)
print (a, b, c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment