use metaclass to decorate errors (#9593)

This commit is contained in:
Bram Vanroy 2021-11-03 15:29:32 +01:00 committed by GitHub
parent c1cc94a33a
commit cab9209c3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 19 deletions

View File

@ -1,18 +1,13 @@
import warnings import warnings
def add_codes(err_cls): class ErrorsWithCodes(type):
"""Add error codes to string messages via class attribute names.""" def __getattribute__(self, code):
msg = super().__getattribute__(code)
class ErrorsWithCodes(err_cls): if code.startswith("__"): # python system attributes like __class__
def __getattribute__(self, code): return msg
msg = super(ErrorsWithCodes, self).__getattribute__(code) else:
if code.startswith("__"): # python system attributes like __class__ return "[{code}] {msg}".format(code=code, msg=msg)
return msg
else:
return "[{code}] {msg}".format(code=code, msg=msg)
return ErrorsWithCodes()
def setup_default_warnings(): def setup_default_warnings():
@ -44,8 +39,7 @@ def _escape_warning_msg(msg):
# fmt: off # fmt: off
@add_codes class Warnings(metaclass=ErrorsWithCodes):
class Warnings:
W005 = ("Doc object not parsed. This means displaCy won't be able to " W005 = ("Doc object not parsed. This means displaCy won't be able to "
"generate a dependency visualization for it. Make sure the Doc " "generate a dependency visualization for it. Make sure the Doc "
"was processed with a model that supports dependency parsing, and " "was processed with a model that supports dependency parsing, and "
@ -194,8 +188,7 @@ class Warnings:
"lead to errors.") "lead to errors.")
@add_codes class Errors(metaclass=ErrorsWithCodes):
class Errors:
E001 = ("No component '{name}' found in pipeline. Available names: {opts}") E001 = ("No component '{name}' found in pipeline. Available names: {opts}")
E002 = ("Can't find factory for '{name}' for language {lang} ({lang_code}). " E002 = ("Can't find factory for '{name}' for language {lang} ({lang_code}). "
"This usually happens when spaCy calls `nlp.{method}` with a custom " "This usually happens when spaCy calls `nlp.{method}` with a custom "

View File

@ -2,11 +2,10 @@ from inspect import isclass
import pytest import pytest
from spacy.errors import add_codes from spacy.errors import ErrorsWithCodes
@add_codes class Errors(metaclass=ErrorsWithCodes):
class Errors:
E001 = "error description" E001 = "error description"