Preventing class methods from being defined
me at privacy.net
Mon Jan 16 12:39:48 CET 2006
On Mon, 16 Jan 2006 21:25:50 +1100,
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
> 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).
By the principle of least surprise, if dir(some_sobject) contains foo,
then some_object.foo should *not* raise a NameError.
All of the posted solutions to the OP's problem could easily be extended
to do something noisy with the (dis-)allowed methods.
More information about the Python-list