Restricting methods in derived classes
Mark McEahern
marklists at mceahern.com
Thu Sep 12 19:17:31 EDT 2002
[Huaiyu Zhu]
> I was hoping for a way to confirm wanted methods, because there are more
> methods that I don't want. But the above is good enough for preventing
> obvious mistakes. Thank you.
Have you considered a metaclass solution? Here's a half-baked attempt that
doesn't work and merely serves to demonstrate how weak my grasp of Python
is. If Alex Martelli is in the house, perhaps he can shed some light. :D
Here's some classic Martelli speak on metaclasses for ya:
http://groups.google.com/groups?selm=mailman.1025801286.31332.python-list%40
python.org
Meanwhile, my lame attempt...
#!/usr/bin/env python
import inspect
def make_unwanted(cls, method_name):
def unwanted(self, *args, **kwargs):
raise AttributeError(cls.__name__, method_name)
return unwanted
class Restricted(type):
def __init__(cls, name, bases, dict):
for base in bases:
for method in inspect.getmembers(base,
inspect.ismethoddescriptor):
if not method[0].startswith('__') and method[1] not in
dict['wanted_methods']:
dict[method[0]] = make_unwanted(cls, method[0])
super(Restricted, cls).__init__(name, bases, dict)
class RestrictedDict(dict):
__metaclass__ = Restricted
wanted_methods = [dict.update]
d = RestrictedDict()
d['a'] = 1
# I expect the following to blow up, but alas, they don't...
for key in d.keys():
print key
d.update({'a': 2})
print d.items()
# Will this give me any clue?
print dir(d)
# Time to go listen to some good music...
// m
More information about the Python-list
mailing list