Skip to content

Instantly share code, notes, and snippets.

@chris-zen
Forked from mstrongdev/ROType.py
Created January 18, 2014 16:42
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 chris-zen/8492907 to your computer and use it in GitHub Desktop.
Save chris-zen/8492907 to your computer and use it in GitHub Desktop.
class ROType(type):
def __new__(mcl, classname, bases, classdict):
class UniqueROType (mcl):
pass
def getAttrFromMetaclass(attr):
return lambda cls: getattr(cls.__metaclass__, attr, None)
for attr, value in classdict.items():
if not hasattr(value, '__call__') and attr.startswith('_') and not attr.startswith('__'):
# Store the private value on the metaclass.
setattr(mcl, attr, value)
# Create a property whose getter queries the attr from the metaclass.
p = property(getAttrFromMetaclass(attr))
# Add the property to our empty metaclass so the correct property
# behavior is generated on the class.
setattr(UniqueROType, attr[1:], p)
# Expose the new 'public' read-only property on the class.
classdict[attr[1:]] = p
# Remove the private value from the class.
classdict.pop(attr, None)
return type.__new__(UniqueROType, classname, bases, classdict)
#
# EXAMPLES
#
class Foo(object):
__metaclass__ = ROType
foo = 0
_bar = 1
_baz = 2
class Test(object):
__metaclass__ = ROType
foo = 'hello'
_bar = 'world'
_baz = 'sam'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment