7

I have a specific problem closely related to PyCharm (Community 3.1.1). The following simple example illustrates this. I will use the screenshot of PyCharm rather than type the code, for reasons that will be clear shortly.

As you can see, the call to self.say_hello() is highlighted in yellow by PyCharm, and presumably this is because say_hello() is not implemented in the Base class. The fact that say_hello() is not implemented in the base class is intentional on my part, because I want a kind of "abstract" effect, so that an instance of Base cannot call say_hello() (and therefore shouldn't call hello()), but that an instance of Child can call hello() (implemented in the Base class). How do I get this "abstract" effect without PyCharm complaining?

As I learned from here, I could use the abc module. But that, to me, would be rather cumbersome and somewhat not pythonic. What are your recommendations?

asked Mar 31, 2014 at 16:17
1
  • Using abstract method seems the only appropriate solution. Commented Mar 31, 2014 at 16:22

1 Answer 1

13

I would implement say_hello() as a stub:

class Base(object):
 # ...as above...
 def say_hello(self):
 raise NotImplementedError

Alternatively, put only pass in the body of say_hello().

This would also signal to the user of your Base class that say_hello() should be implemented before she gets an AttributeError when calling obj.hello(). Whether to raise an Exception or to pass depends on whether doing nothing is sensible default behaviour. If you require the user to supply her own method, raise an exception.

answered Mar 31, 2014 at 16:29
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.