Skip to content

Instantly share code, notes, and snippets.

@pingzh
Created July 22, 2022 00:37
Show Gist options
  • Save pingzh/2fcb3cc71acbfaf4222e0225d6f63202 to your computer and use it in GitHub Desktop.
Save pingzh/2fcb3cc71acbfaf4222e0225d6f63202 to your computer and use it in GitHub Desktop.
def protect(*protected):
"""Returns a metaclass that protects all attributes given as strings"""
class Protect(type):
has_base = False
def __new__(meta, name, bases, attrs):
if meta.has_base:
for attribute in attrs:
if attribute in protected:
raise AttributeError('Overriding of attribute "%s" not allowed.'%attribute)
meta.has_base = True
klass = super().__new__(meta, name, bases, attrs)
return klass
return Protect
class Parent(metaclass=protect("do_something", "do_something_else")):
def do_something(self):
'''This is where some seriously important stuff goes on'''
pass
class Child(Parent):
def do_something(self):
'''This will raise an error during class creation.'''
pass
c = Child()
c.do_something()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment