|
| 1 | +from typing import TYPE_CHECKING, Any |
| 2 | + |
1 | 3 | import astroid
|
2 | 4 | from astroid import MANAGER
|
3 | 5 |
|
| 6 | +if TYPE_CHECKING: |
| 7 | + from pylint.lint import PyLinter |
| 8 | + |
4 | 9 |
|
5 |
| -def register(linter: None) -> None: |
6 |
| - """Required for registering the plugin""" |
7 |
| - pass |
| 10 | +def register(linter: "PyLinter") -> None: |
| 11 | + """Register the plugin.""" |
8 | 12 |
|
9 | 13 |
|
10 |
| -def transform(cls: astroid.ClassDef) -> None: |
11 |
| - """ " Add ScanningInstrument methods to the declaring module |
| 14 | +def transform(node: astroid.ClassDef, *args: Any, **kwargs: Any) -> None: |
| 15 | + """Add ScanningInstrument methods to the declaring module. |
12 | 16 |
|
13 | 17 | If the given class is derived from ScanningInstrument,
|
14 | 18 | get all its public methods and, for each one, add a dummy method
|
15 | 19 | with the same name to the module where the class is declared (note: adding a reference
|
16 | 20 | to the actual method rather than a dummy will cause the linter to crash).
|
17 | 21 | """
|
18 |
| - if cls.basenames and "ScanningInstrument" in cls.basenames: |
19 |
| - public_methods = filter(lambda method: not method.name.startswith("__"), cls.methods()) |
| 22 | + if node.basenames and "ScanningInstrument" in node.basenames: |
| 23 | + public_methods = filter(lambda method: not method.name.startswith("__"), node.methods()) |
20 | 24 | for public_method in public_methods:
|
21 |
| - cls.parent.locals[public_method.name] = astroid.FunctionDef( |
22 |
| - name=public_method.name, |
23 |
| - lineno=0, |
24 |
| - col_offset=0, |
25 |
| - parent=cls.parent, |
26 |
| - end_lineno=0, |
27 |
| - end_col_offset=0, |
28 |
| - ) |
| 25 | + if isinstance(node.parent, astroid.Module): |
| 26 | + new_func = astroid.FunctionDef( |
| 27 | + name=public_method.name, |
| 28 | + lineno=0, |
| 29 | + col_offset=0, |
| 30 | + parent=node.parent, |
| 31 | + end_lineno=0, |
| 32 | + end_col_offset=0, |
| 33 | + ) |
| 34 | + arguments = astroid.Arguments( |
| 35 | + vararg=None, |
| 36 | + kwarg=None, |
| 37 | + parent=new_func, |
| 38 | + ) |
| 39 | + arguments.postinit( |
| 40 | + args=None, |
| 41 | + defaults=None, |
| 42 | + kwonlyargs=[], |
| 43 | + kw_defaults=None, |
| 44 | + annotations=[], |
| 45 | + posonlyargs=[], |
| 46 | + kwonlyargs_annotations=[], |
| 47 | + posonlyargs_annotations=[], |
| 48 | + ) |
| 49 | + new_func.postinit(args=arguments, body=[]) |
| 50 | + node.parent.locals[public_method.name] = [new_func] |
29 | 51 |
|
30 | 52 |
|
31 | 53 | MANAGER.register_transform(astroid.ClassDef, transform)
|
0 commit comments