Are you using python3 to run that code? If yes, you should know that declaring metaclass in python3 have changes you should do it like this instead:

import abc

class AbstractClass(metaclass=abc.ABCMeta):

  @abc.abstractmethod
  def abstractMethod(self):
      return

The full code and the explanation behind the answer is:

import abc

class AbstractClass(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def abstractMethod(self):
        return

class ConcreteClass(AbstractClass):

    def __init__(self):
        self.me = "me"

# Will get a TypeError without the following two lines:
#   def abstractMethod(self):
#       return 0

c = ConcreteClass()
c.abstractMethod()

If abstractMethod is not defined for ConcreteClass, the following exception will be raised when running the above code: TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod

Answer from mouad on Stack Overflow
🌐
Python
docs.python.org › 3 › library › abc.html
abc — Abstract Base Classes
A class that has a metaclass derived ... the normal ‘super’ call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors....
🌐
Medium
medium.com › @ankitlodh2002 › exploring-pythons-abstraction-abstract-methods-decorators-and-magic-methods-demystified-2c6ec5e14dce
Exploring Python’s Abstraction: Abstract Methods, Decorators, and Magic Methods Demystified | by Ankit Lodh | Medium
December 16, 2023 - Now you are equipped with the concept of decorator it is time to explore abstract methods in Python. Below is the example code to follow — · from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): return "area is not created inherit this function" class Circle(Shape): def __init__(self,radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 class Square(Shape): def __init__(self,side_length): self.side_length = side_length def area3(self): print(self.area()) return self.side_length**2 # instantiation of circle and square class circle = Circle(5) square = Square(5)
🌐
Reddit
reddit.com › r/learnpython › decorating an abstractmethod.
r/learnpython on Reddit: decorating an abstractmethod.
June 14, 2024 -

I have the class inheritance going on like this...

     Base
      |
     Sub
      |
  ---------
  |       |
TaskA   TaskB

Base implements some loggers and Sub implements the config and Tasks implements the run methods. I wanted to catch all the exceptions raised by the tasks and handle them and return False.

I was hoping I would decorate the abstractmethod with a custom decorator so that I don't need all the inheriting Tasks to decorate them. But it is not working as expected.

from abc import ABC, abstractmethod
from functools import wraps

def catch_exceptions_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            self = args[0]
            self.log_error("Error running the task.", e)
            return False
    return wrapper

class Base(ABC):

    def log_error(self, message, exception):
        """Log error."""
        print(f"ERROR: {message} {exception}")

    @abstractmethod
    def configure(self):
        """Configure."""
        pass

class Sub(Base):

    def configure(self):
        """Configure."""
        print("Configuring.")

    @abstractmethod
    @catch_exceptions_decorator
    def run(self):
        """Run."""
        pass

class TaskA(Sub):

    def run(self):
        """Run."""
        raise KeyError
        print("Running.")
        return True

task = TaskA()
assert not taskA.run()

I was expecting the KeyError to be caught by the catch_exceptions_decorator and return False insted of raising the exception as shown below.

Traceback (most recent call last):
  File "/Users/X/Desktop/abc_decorator.py", line 47, in <module>
    assert not task.run()
               ^^^^^^^^^^
  File "/Users/X/Desktop/abc_decorator.py", line 43, in run
    raise KeyError
KeyError

What am I doing wrong here ?

EDIT: Ended up using a metaclass and here is the final code if that's helpful to anyone.

from abc import ABC, ABCMeta, abstractmethod
from functools import wraps
from operator import call
from textwrap import wrap


class TaskMeta(type):

    def __new__(cls, name, bases, attrs):
        """Metaclass for tasks."""

        for attr_name, attr_value in attrs.items():
            if attr_name == "run" and callable(attr_value):
                attrs[attr_name] = cls.catch_exceptions_decorator(attr_value)
        return super().__new__(cls, name, bases, attrs)

    @staticmethod
    def catch_exceptions_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                self = args[0]
                self.log_error("Error running the task.", e)
                return False
        return wrapper


class BaseMeta(ABCMeta, TaskMeta):
    pass


class Base(metaclass=BaseMeta):

    def log_error(self, message, exception):
        """Log error."""
        print(f"ERROR: {message} {exception}")

    @abstractmethod
    def configure(self):
        """Configure."""
        pass


class Sub(Base):

    def configure(self):
        """Configure."""
        print("Configuring.")

    @abstractmethod
    def run(self):
        """Run."""
        pass


class Task(Sub):

    def run(self):
        """Run."""
        raise KeyError
        print("Running.")
        return True


task = Task()
assert not task.run()

Prints the error instead of raising exception.

ERROR: Error running the task. 
🌐
Python
peps.python.org › pep-3119
PEP 3119 – Introducing Abstract Base Classes | peps.python.org
The abc module also defines a new decorator, @abstractmethod, to be used to declare abstract methods. A class containing at least one method declared with this decorator that hasn’t been overridden yet cannot be instantiated.
🌐
Object-oriented-python
object-oriented-python.github.io › 10_further_object-oriented_features.html
10. Further object-oriented features — Object-oriented Programming documentation
Listing 10.2 An abstract base class version of the Group class. Note that the class itself inherits from ABC, and the methods and attribute to be implemented by the child classes have the abstractmethod decorator.¶
🌐
The Teclado Blog
blog.teclado.com › python-abc-abstract-base-classes
How to Write Cleaner Python Code Using Abstract Classes
October 26, 2022 - To define an abstract method in the abstract class, we have to use a decorator: @abstractmethod.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › abstract-classes-in-python
Abstract Classes in Python - GeeksforGeeks
Abstract properties work like abstract methods but are used for properties. These properties are declared with the @property decorator and marked as abstract using @abstractmethod.
Published   September 3, 2025
🌐
Python Course
python-course.eu › oop › the-abc-of-abstract-base-classes.php
20. The 'ABC' of Abstract Base Classes | OOP | python-course.eu
from abc import ABC, abstractmethod class AbstractClassExample(ABC): def __init__(self, value): self.value = value super().__init__() @abstractmethod def do_something(self): pass · We will define now a subclass using the previously defined abstract class. You will notice that we haven't implemented the do_something method, even though we are required to implement it, because this method is decorated as an abstract method with the decorator "abstractmethod".
🌐
DataCamp
datacamp.com › tutorial › python-abstract-classes
Python Abstract Classes: A Comprehensive Guide with Examples | DataCamp
January 22, 2025 - The class is abstract and cannot be instantiated directly, as indicated by this inheritance. By acting as blueprints, abstract classes make sure that any concrete subclass abides by a set of rules. You can define abstract methods inside an abstract class by using the abstractmethod decorator.
🌐
Ikriv
ikriv.com › blog
Python: the land of abstract static methods – Ivan Krivyakov
@abstractmethod is a regular decorator that can technically be applied to any function or class. It is only checked by the constructor of abc.ABC. Any occurrences of @abstractmethod outside of classes descending from abc.ABC are ignored. All of the following is legal in Python as of version ...
🌐
datagy
datagy.io › home › python posts › python abc: abstract base class and abstractmethod
Python abc: Abstract Base Class and abstractmethod • datagy
December 23, 2022 - In order to create abstract classes in Python, we can use the built-in abc module. The module provides both the ABC class and the abstractmethod decorator.
🌐
ActiveState
code.activestate.com › recipes › 577666-abstract-method-decorator
Abstract method decorator « Python recipes « ActiveState Code
A simple decorator that helps define abstract methods: when such a method is called, an appropriate exception is raised · I find it more consistent that the (nonetheless elegant): def foo(self): abstract
🌐
30 Days Coding
30dayscoding.com › blog › abc-import-abc-abstractmethod-python
Understanding ABC Import and ABC AbstractMethod in ...
The `ABC` class is the base class for all abstract classes in Python. When you define a class that inherits from `ABC`, it becomes an abstract class that cannot be instantiated on its own. The `abstractmethod` decorator is used to define abstract methods within an abstract class.
🌐
W3Schools
w3schools.com › python › ref_module_abc.asp
Python abc Module
Python Examples Python Compiler ... print(sq.area()) Try it Yourself » · The abc module provides tools for creating Abstract Base Classes (ABCs) and decorators for abstract methods....
🌐
Scaler
scaler.com › home › topics › abstract class in python
Abstract Class in Python - Scaler Topics
April 9, 2024 - Here we just need to inherit the ABC class from the abc module in Python. Now, let's take the following example to demonstrate abstract classes: To define an abstract method we use the @abstractmethod decorator of the abc module.