Can a base class know if a method has been overridden?
Michele Simionato
michele.simionato at gmail.com
Mon Sep 24 11:44:40 EDT 2007
On Sep 24, 5:23 pm, Ratko <rjago... at gmail.com> wrote:
> Hi all,
>
> I was wondering if something like this is possible. Can a base class
> somehow know if a certain method has been overridden by the subclass?
> I appreciate any ideas.
> Thanks,
>
> Ratko
The first time I used Zope, I immediately had an issue of overriding a
predefined
methods without knowing it (there were 400+ methods inherited from
dozens of base
classes). So I wrote this utility:
def check_if_I_am_overriding_names():
"""Prints a message if we are overriding a name. Useful for
framework
beginners. Example in Zope:
>> from OFS.Folder import Folder
>> class MyFolder(OFS.Folder):
.. check_if_I_am_overriding_names()
.. id = 'pippo'
..
AlreadyDefinedNameWarning: id
"""
def makecls(name, bases, dic):
for nam, val in dic.iteritems():
if nam.endswith("__") or nam == "meta_types":
# ignore redefinitions of special names
# and redefinition of meta_types (for Zope code)
continue
any_base_has_name = [base for base in bases
if hasattr(base, nam)]
if any_base_has_name:
print "AlreadyDefinedNameWarning: " + nam
return type(name, bases, dic)
f = sys._getframe(1)
f.f_locals["__metaclass__"] = makecls
Michele Simionato
More information about the Python-list
mailing list