Skip to content

Instantly share code, notes, and snippets.

@GaretJax
Created July 15, 2011 20:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GaretJax/1085475 to your computer and use it in GitHub Desktop.
Save GaretJax/1085475 to your computer and use it in GitHub Desktop.
import inspect
def NameAwareClassType():
frameInfo = inspect.getouterframes(inspect.currentframe())[1]
codeContext = frameInfo[4][0]
className = codeContext.split(' ', 1)[1].split('(', 1)[0]
g = globals()
class ClassName(object):
def __init__(self, className):
self.className = className
def __str__(_self):
if _self.className:
return _self.className
frames = inspect.getouterframes(inspect.currentframe())
for frame in frames:
if 'self' in frame[0].f_locals:
return frame[0].f_locals['self'].__class__.__name__
raise NameError("name '__clsname__' is not defined")
def __repr__(self):
return 'ClassName({0})'.format(self.className)
g['__clsname__'] = ClassName(className)
class ClassNameGlobalRemoverType(type):
def __new__(mcs, name, bases, dict):
if name == className:
g['__clsname__'].className = None
return type.__new__(mcs, name, bases, dict)
class NameAwareClass(object):
__metaclass__ = ClassNameGlobalRemoverType
return NameAwareClass
class A(NameAwareClassType()):
print "Class name of A is:", __clsname__
def __init__(self):
print "Inside the __init__ of A, the name is:", str(__clsname__)
class B(NameAwareClassType()):
print "Class name of B is:", __clsname__
def __init__(self):
print "Inside the __init__ of B, the name is:", str(__clsname__)
try:
print __clsname__
except Exception as e:
print '__clsname__ is not defined outside of a class declaration'
print ' --> Printing failed with error', repr(e)
A()
B()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment