Created
November 19, 2024 06:13
-
-
Save dibrinsofor/bddcbd2eedbb233b131bb1b8d562369a to your computer and use it in GitHub Desktop.
mypy plugin to replace types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>> mypy --show-traceback tests/str_int.py | |
final def (a: builtins.str) -> builtins.int | |
final <class 'mypy.nodes.FuncDef'> | |
final def (a: builtins.str) -> builtins.int | |
final <class 'mypy.nodes.FuncDef'> | |
tests/str_int.py:2: error: Incompatible return value type (got "int", expected "str") [return-value] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mypy.plugin import ( | |
Plugin, | |
FunctionSigContext, | |
FunctionLike | |
) | |
from mypy.nodes import FuncDef | |
from typing_extensions import Callable | |
from types import FunctionType | |
class CustomPlugin(Plugin): | |
def get_function_signature_hook( | |
self, fullname: str | |
) -> Callable[[FunctionSigContext], FunctionLike] | None: | |
if "almost_id" in fullname: | |
return self.replace_str | |
return None | |
def replace_str(self, ctx: FunctionSigContext) -> FunctionLike: | |
api = ctx.api | |
new_signature = ctx.default_signature.copy_modified( | |
ret_type=api.named_type('builtins.int') | |
) | |
un_anal = new_signature.definition.unanalyzed_type.copy_modified( | |
ret_type = api.named_type('builtins.int') | |
) | |
new_signature.definition.unanalyzed_type = un_anal | |
typ = new_signature.definition.type.copy_modified( | |
ret_type = api.named_type('builtins.int') | |
) | |
new_signature.definition.type = typ | |
print("final", new_signature) | |
print("final", type(new_signature.definition)) | |
return new_signature | |
def plugin(version: str) -> Plugin: | |
return CustomPlugin #type: ignore |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def almost_id(a: str) -> str: | |
return int(a) | |
almost_id("some") | |
almost_id("6") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment