python - Non-callable subclass of a callable class -


i have class a callable. have subclass of a called b want make not callable. should raise normal "not callable" typeerror when try call it.

class a():     def __call__(self):         print "i did it"  class b(a):     def __call__(self):         raise typeerror("'b' object not callable") 

as can see, solution right raise duplicate of normal typeerror. feels wrong, since i'm copying text of standard python exception. better (in opinion) if there way mark subclass not callable , have python handle attribute.

what best way make class b not callable, given it's subclass of callable class a?

you can override type creation python metaclasses. here after object creation, replace parent's __call__ method 1 throwing exception:

>>> class a(object):     def __call__(self):         print 'called !'   >>> class metanotcallable(type):     @staticmethod     def call_ex(*args, **kwargs):             raise notimplementederror()      def __new__(mcs, name, bases, dict):         obj = super(metanotcallable, mcs).__new__(mcs, name, bases, dict)         obj.__call__ = metanotcallable.call_ex # change method !         return obj   >>> class b(a):     __metaclass__ = metanotcallable   >>> = a() >>> a() called ! >>> b = b() >>> b()  traceback (most recent call last):   file "<pyshell#131>", line 1, in <module>     b()   file "<pyshell#125>", line 4, in call_ex     raise notimplementederror() notimplementederror 

Comments