Skip to content

Commit 77da152

Browse files
authored
Use __init_subclass__ for subclass registration (#237)
Python 3.6 introduced __init_subclass__(cls), which provides a nicer subclass registration pattern than the previous metaclass-based approach.
1 parent 0308d09 commit 77da152

File tree

1 file changed

+21
-23
lines changed

1 file changed

+21
-23
lines changed

src/pep8ext_naming.py

+21-23
Original file line numberDiff line numberDiff line change
@@ -31,33 +31,31 @@
3131
FUNC_NODES = (ast.FunctionDef, ast.AsyncFunctionDef)
3232

3333

34-
class _ASTCheckMeta(type):
35-
def __init__(cls, class_name, bases, namespace):
36-
cls.codes = tuple(code for code in namespace if code.startswith('N'))
37-
try:
38-
cls.all.append(cls())
39-
except AttributeError:
40-
cls.all = []
41-
42-
43-
def _err(self, node, code, **kwargs):
44-
lineno, col_offset = node.lineno, node.col_offset
45-
if isinstance(node, ast.ClassDef):
46-
col_offset += 6
47-
elif isinstance(node, FUNC_NODES):
48-
col_offset += 4
49-
code_str = getattr(self, code)
50-
if kwargs:
51-
code_str = code_str.format(**kwargs)
52-
return lineno, col_offset + 1, f'{code} {code_str}', self
34+
class BaseASTCheck:
35+
"""Base for AST Checks."""
5336

37+
all: list['BaseASTCheck'] = []
38+
codes: tuple[str, ...]
5439

55-
def _ignored(name, ignore):
56-
return any(fnmatchcase(name, i) for i in ignore)
40+
def __init_subclass__(cls, **kwargs):
41+
super().__init_subclass__(**kwargs)
42+
cls.all.append(cls())
43+
cls.codes = tuple(code for code in dir(cls) if code.startswith('N'))
5744

45+
def err(self, node, code: str, **kwargs):
46+
lineno, col_offset = node.lineno, node.col_offset
47+
if isinstance(node, ast.ClassDef):
48+
col_offset += 6
49+
elif isinstance(node, FUNC_NODES):
50+
col_offset += 4
51+
code_str = getattr(self, code)
52+
if kwargs:
53+
code_str = code_str.format(**kwargs)
54+
return lineno, col_offset + 1, f'{code} {code_str}', self
5855

59-
BaseASTCheck = _ASTCheckMeta('BaseASTCheck', (object,),
60-
{'__doc__': "Base for AST Checks.", 'err': _err})
56+
57+
def _ignored(name, ignore):
58+
return any(fnmatchcase(name, i) for i in ignore)
6159

6260

6361
class _FunctionType:

0 commit comments

Comments
 (0)