Restricting methods in derived classes

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Sep 13 18:32:52 EDT 2002


Mark McEahern <marklists at mceahern.com> wrote:
>Huaiyu,
>
>I feel compelled to gently ask, "What's the point of this rigamarole?"

Maybe to show how to make a solution larger than the problem itself?  :-)
But seriously, your first solution actually contains all I needed.  Here's
what I adopted in the end:

def undefined(self, *args, **kwargs):
	raise NotImplementedError

_common = ['__class__', '__defined__', '__dict__', '__doc__',
			'__getattribute__', '__init__', '__new__']

def restrict(foo):
	for a in dir(foo):
		if a not in _common + foo.__defined__:
			setattr(foo, a, undefined)

class foo(dict):
	def __init__(self, *args):	print "foo", args
	def put(self, x):		pass
	__defined__ = ['put', 'get', 'keys', 'items', 'values']

restrict(foo)

if __name__ == '__main__':
	f = foo()
	print f.keys
	print f.keys()
	f['a'] = 'b'

Maybe there is a simple way to wrap up restrict() in a metaclass, so that
instead of restrict(foo) we can say class foo(dict, restricted): ...
I'm still not so used to metaclasses to figure that out, however.

Huaiyu



More information about the Python-list mailing list