1

I know I can implement in the base class some function to raise when subclass fails to override some method.

def some_method( self ):
  raise NotImplementedError

But how can I do the opposite, i.e. raise only when the subclass does override this method?

Thanks!

Edit: I'm trying to prevent people from overriding getitem/getattr so the namespace clash doesn't apply here.

Edit: I already tried to check if the subclass method is base class method. This worked under CPython, but not PyPy. Is there any all-around solution?

3 Answers3

1

One way of solving this problem is to use a meta-class and then check during creation, if the method is part of the body and raise a typeError

class BaseMeta(type):
    def __new__(cls, name, bases, body):
        if 'bar' in body:
            raise TypeError("bad user class")
        return super().__new__(cls, name, bases, body)


class Base(metaclass=BaseMeta):
    def bar(self):
        return None


class Derived(object):
    def bar(self):
        return 'bar'
user1767754
  • 23,311
  • 18
  • 141
  • 164
0

You can check whether the method is the same method object as the superclass:

def is_base_impl(obj):
    return obj.__getattr__ is BaseClass.__getattr__

Of course, this only detects unintentional overriding; if a subclass were determined to do this they could just monkey-patch BaseClass instead.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
  • This is what I had, worked with CPython, but not PyPy ... But anyways thanks for the help! – Shunning Jiang Dec 26 '17 at 01:58
  • 2
    In the presence of a JIT all bets are off. You should have put that relevant information in your question in the first place: both that you had tried this and what platform you are using. – Daniel Pryden Dec 26 '17 at 01:59
  • 2
    Honestly, you should not have accepted this answer if it didn't actually answer your question. – Daniel Pryden Dec 26 '17 at 02:00
  • 1
    Can't believe this is what you want... So you think those guys who don't know how to use your lib correctly are smart enough to use this function to check if they are doing wrongly? IMHO, you just need to believe them or writing a well-formatted document. – Sraw Dec 26 '17 at 02:02
  • Thanks for the suggestion. Already updated the question. I thought it was just because I was doing the wrong thing and there might be Pythonic all-around solution. – Shunning Jiang Dec 26 '17 at 02:08
0

At __init__() time you could use inspect.getmembers() to learn details about some_method(). Then you could choose to test the method's behavior or report on it as needed.

J_H
  • 17,926
  • 4
  • 24
  • 44