Preventing class methods from being defined

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Jan 16 05:25:50 EST 2006


On Sun, 15 Jan 2006 18:41:02 -0800, David Hirschfield wrote:

> Here's a strange concept that I don't really know how to implement, but 
> I suspect can be implemented via descriptors or metaclasses somehow:
> 
> I want a class that, when instantiated, only defines certain methods if 
> a global indicates it is okay to have those methods.

Others have already made suggestions, here is a third:


class A:
    def foo(self):
        print "Foo!"
    def bar(self):
        print "Bar!"
    def baz(self):
        print "Baz!"
    __all__ = [x.__name__ for x in (foo, bar, baz)]
    def __null(self, name="<unknown>", *args, **kwargs):
        raise NameError("Method '%s' was disabled at init time." % name)
    def __init__(self, data=None):
        global permitted # not strictly needed, but I prefer it 
        for method in self.__all__:
            if method not in permitted:
                # if you are clever, use currying to bind the name of 
                # the method to the first arg of __null so it gives a 
                # more useful error message
                setattr(self, method, self.__null)
        # local initialisation
        self.x = data


The main disadvantage of this I can see is that dir(A()) still reports
methods foo, bar, baz even if they have been disabled. But maybe that's
better behaviour than just making them disappear (principle of least
surprise: better to explicitly report that something is disabled than to
just have it magically appear and disappear).


-- 
Steven.




More information about the Python-list mailing list