What is proper way to require a method to be overridden?

C

Carl Banks

Fuzzyman said:
Well...

How about not defining it on the base class, but check in the
constructor that the attribute exists and that it is of type
FunctionType ?

That still delays the check until the object is created.

You'd have to use metaclass programming to check this during class
creation time.


Carl Banks
 
S

sjdevnull

Patrick said:
Decorators to the rescue?

def must_override(f):
def t(*args):
raise NotImplementedError("You must override " + f.__name__)
return t

class Foo:
@must_override
def Bar(x,y): pass

Foo().Bar()

Traceback (most recent call last):
File "testit.py", line 14, in ?
Foo().Bar()
File "testit.py", line 5, in t
raise NotImplementedError("You must override " + f.__name__)
NotImplementedError: You must override Bar

I'd think twice before using a decorator. This just seems less clear
to read than simply raising NotImplementedError, and the traceback
points into the decorator instead of the function that you really care
about.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top