pythondjangochain-of-responsibility

Django 'Handler' is not defined


I'm currently working on a Django REST project, and trying to implement the Chain of responsibility pattern on it.

Since I downgraded my Python version from 3.9.2 to 3.6.5, I've encountered another problem, which is the following:

 NameError: name 'Handler' is not defined

And this is the code where the error is:

from abc import ABCMeta, abstractmethod
from typing import Any, Optional

class Handler(metaclass=ABCMeta):
    """
    The Handler interface declares a method for building the chain of handlers.
    It also declares a method for executing a request.
    """

    @abstractmethod
    def set_next(self, handler: Handler) -> Handler:
        pass

    @abstractmethod
    def handle(self, request) -> Optional[str]:
        pass

How can I fix it?


Solution

  • The issue here is that you are using a not-yet defined type Handler to annotate one of its methods. Add this import to the top of your file to fix this:

    from __future__ import annotations
    

    You will be able to remove it on Python 3.10 and later. See https://www.python.org/dev/peps/pep-0563/#implementation for details.