2

I am just trying to practice coding an abstract method in Python and i have the following code for it:

import abc
class test(abc.ABC):
 @abc.abstractmethod
 def first(self,name):
 """This is to be implemented"""
class Extendtest(test):
 def __init__(self,name):
 self.name = name
 def first(self):
 print ("Changing name!")
 self.name = "Shaayan"
 def second(self,value):
 print ("Adding second argument!")
 self.value = value
e = Extendtest("Subhayan")
print (e.name) 
e.first()
print (e.name)

I intentionally changed the signature of the first method in the implementation of the abstract method.

But if i change the signature Python is not giving any error and is going through as expected.

Is there no way in Python by which i can force strict abstraction ?

Patrick Trentin
7,3723 gold badges26 silver badges44 bronze badges
asked May 27, 2017 at 15:05
1
  • In Python abstract methods are not necessary. Just use duck-typing. Commented May 27, 2017 at 15:25

1 Answer 1

1

This is not a new question asked about python and a short answer:

No, it is not possible. The easiest way is either to reuse a custom library like zope or implement this behavior by your own.

There was a proposal on ABC to check arguments and here is what Guido answers on this:

That is not a new idea. So far I have always rejected it because I worry about both false positives and false negatives. Trying to enforce that the method behaves as it should (or even its return type) is hopeless; there can be a variety of reasons to modify the argument list while still conforming to (the intent of) the interface. I also worry that it will slow everything down.

That said, if you want to provide a standard mechanism that can optionally be turned on to check argument conformance, e.g. by using a class or method decorator on the subclass, I would be fine with that (as long as it runs purely at class-definition time; it shouldn't slow down class instantiation or method calls). It will probably even find some bugs. It will also surely have to be tuned to avoid certain classes false positives.

reference to the thread

answered May 27, 2017 at 15:12
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.