masterPiece93 / PythonEssentials

0 stars 0 forks source link

IDEA : restricting method overriding in child classes . #6

Open masterPiece93 opened 9 months ago

masterPiece93 commented 9 months ago
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
masterPiece93 commented 9 months ago

Point of View on restrict overriding which is not simply possible in python :

You are right: what you are attempting is contrary to Python's structure and its culture.

Document your API, and educate your users how to use it. It's their program, so if they still want to override your function, who are you to prevent them?

  1. just write function doc-strings not to override .
  2. prepend such methods with __ (double_underscore)