-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Add type checking plugin support for functions #3299
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
"""Plugins that implement special type checking rules for individual functions. | ||
|
||
The plugins infer better types for tricky functions such as "open". | ||
""" | ||
|
||
from typing import Tuple, Dict, Callable, List | ||
|
||
from mypy.nodes import Expression, StrExpr | ||
from mypy.types import Type, Instance, CallableType | ||
|
||
|
||
# A callback that infers the return type of a function with a special signature. | ||
# | ||
# A no-op callback would just return the inferred return type, but a useful callback | ||
# at least sometimes can infer a more precise type. | ||
PluginCallback = Callable[ | ||
[ | ||
List[List[Type]], # List of types caller provides for each formal argument | ||
List[List[Expression]], # Actual argument expressions for each formal argument | ||
Type, # Return type for call inferred using the regular signature | ||
Callable[[str, List[Type]], Type] # Callable for constructing a named instance type | ||
], | ||
Type # Return type inferred by the callback | ||
] | ||
|
||
|
||
def get_function_plugin_callbacks(python_version: Tuple[int, int]) -> Dict[str, PluginCallback]: | ||
"""Return all available function plugins for a given Python version.""" | ||
if python_version[0] == 3: | ||
return { | ||
'builtins.open': open_callback, | ||
'contextlib.contextmanager': contextmanager_callback, | ||
} | ||
else: | ||
return { | ||
'contextlib.contextmanager': contextmanager_callback, | ||
} | ||
|
||
|
||
def open_callback( | ||
arg_types: List[List[Type]], | ||
args: List[List[Expression]], | ||
inferred_return_type: Type, | ||
named_generic_type: Callable[[str, List[Type]], Type]) -> Type: | ||
"""Infer a better return type for 'open'. | ||
|
||
Infer IO[str] or IO[bytes] as the return value if the mode argument is not | ||
given or is a literal. | ||
""" | ||
mode = None | ||
if not arg_types or len(arg_types[1]) != 1: | ||
mode = 'r' | ||
elif isinstance(args[1][0], StrExpr): | ||
mode = args[1][0].value | ||
if mode is not None: | ||
assert isinstance(inferred_return_type, Instance) | ||
if 'b' in mode: | ||
arg = named_generic_type('builtins.bytes', []) | ||
else: | ||
arg = named_generic_type('builtins.str', []) | ||
return Instance(inferred_return_type.type, [arg]) | ||
return inferred_return_type | ||
|
||
|
||
def contextmanager_callback( | ||
arg_types: List[List[Type]], | ||
args: List[List[Expression]], | ||
inferred_return_type: Type, | ||
named_generic_type: Callable[[str, List[Type]], Type]) -> Type: | ||
"""Infer a better return type for 'contextlib.contextmanager'.""" | ||
# Be defensive, just in case. | ||
if arg_types and len(arg_types[0]) == 1: | ||
arg_type = arg_types[0][0] | ||
if isinstance(arg_type, CallableType) and isinstance(inferred_return_type, CallableType): | ||
# The stub signature doesn't preserve information about arguments so | ||
# add them back here. | ||
return inferred_return_type.copy_modified( | ||
arg_types=arg_type.arg_types, | ||
arg_kinds=arg_type.arg_kinds, | ||
arg_names=arg_type.arg_names) | ||
return inferred_return_type |
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I just realized that that class is misnamed in typeshed, it should be
_GeneratorContextManager
(to match what it's called at runtime). I also don't understand what its__call__
method is for (contextlib doesn't seem to have reference docs, and the source has few clues).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
__call__
is so that@contextmanager
-decorated functions can also be used as decorators themselves (executing the decorated function within the context). Nick Coghlan has said that he considers this feature a design mistake in contextlib.