8000 Basic ParamSpec Concatenate and literal support by A5rocks · Pull Request #11847 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Basic ParamSpec Concatenate and literal support #11847

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 50 commits into from
Apr 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
ef32680
Add ParamSpec literals
A5rocks Dec 24, 2021
816f3cd
Improve ParamSpec and Parameters checking
A5rocks Dec 25, 2021
d9b352f
Get basic Concatenate features working
A5rocks Dec 26, 2021
58e6dbe
Fix "cache" bug
A5rocks Dec 26, 2021
51ba4ea
Check Concatenate prefixes
A5rocks Dec 26, 2021
24432ee
Polish work
A5rocks Dec 26, 2021
c507152
Merge branch 'master' into paramspec-literals
A5rocks Dec 26, 2021
d202d1e
Tests for literals
A5rocks Dec 26, 2021
9ed9830
Tests for Concatenate
A5rocks Dec 26, 2021
3ffc343
Appease CI
A5rocks Dec 26, 2021
ae8ac73
Forgot to comment out the directives...
A5rocks Dec 26, 2021
9c849cc
Improve literal TODOs
A5rocks Dec 27, 2021
d9dcc76
Add more tests
A5rocks Dec 28, 2021
0e2b207
Allow TypeVars in Concatenate
A5rocks Dec 28, 2021
bd445e5
Fix a couple of dumb oversights
A5rocks Dec 28, 2021
604c304
Allow Callables along with Parameters
A5rocks Dec 28, 2021
f8004ec
Fix tests
A5rocks Dec 28, 2021
9e75481
Misc changes
A5rocks Dec 29, 2021
7b89f06
Solve with self types
A5rocks Jan 1, 2022
f24cf4f
Add fallback return to meeting paramspec literals
A5rocks Jan 1, 2022
472b20c
Type application of ParamSpec literals
A5rocks Jan 3, 2022
14ecfb9
Ellipsis paramspec literals
A5rocks Jan 3, 2022
5e0ae49
Merge branch 'master' into paramspec-literals
A5rocks Jan 3, 2022
45c8057
Appease flake8
A5rocks Jan 3, 2022
10966ea
Merge branch 'master' into paramspec-literals
hauntsaninja Jan 7, 2022
c46feec
Minor code cleanup
A5rocks Jan 9, 2022
6a9cd71
Error notes and better subtyping for paramspec literals
A5rocks Jan 9, 2022
afc1a57
Appease CI
A5rocks Jan 9, 2022
41e38b2
Merge remote-tracking branch 'upstream/master' into paramspec-literals
A5rocks Jan 19, 2022
86e23c2
Fix something I assumed incorrectly
A5rocks Jan 27, 2022
3f4cf5c
Merge branch 'master' into paramspec-literals
A5rocks Jan 27, 2022
61b00cd
Revert "Minor code cleanup"
A5rocks Jan 29, 2022
9c2cefd
Merge branch 'master' into paramspec-literals
A5rocks Mar 1, 2022
a44937b
Fixed raised bugs
A5rocks Mar 1, 2022
bbabbf1
Fix CI errors
A5rocks Mar 1, 2022
ddfd34a
Squash some more bugs
A5rocks Mar 5, 2022
2d54ac4
Concatenate flag
A5rocks Mar 5, 2022
bba91e5
Prepare for GitHub Actions
A5rocks Mar 5, 2022
e0a7663
Merge branch 'master' into paramspec-literals
A5rocks Mar 7, 2022
0363803
Bug report with nested decorators and Concatenate
A5rocks Mar 7, 2022
278b8c4
Switch over to using Parameters instead of CallableType
A5rocks Mar 7, 2022
c2b7628
Add variance to paramspecs
A5rocks Mar 7, 2022
0b1fdfb
Apply suggestions from code review
A5rocks Mar 10, 2022
0fff609
Update tests
A5rocks Mar 10, 2022
4475515
Some of the PR feedback
A5rocks Mar 25, 2022
0091762
Merge branch 'master' into paramspec-literals
A5rocks Mar 26, 2022
81994f1
Prepare for GitHub actions
A5rocks Mar 26, 2022
1ff96c1
Merge branch 'master' into paramspec-literals
A5rocks Apr 5, 2022
c79918e
Fix tests to latest output
A5rocks Apr 5, 2022
9b1fc75
Copy pyright's representation of Concatenate
A5rocks Apr 5, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Squash some more bugs
Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  • Loading branch information
A5rocks and cdce8p committed Mar 5, 2022
commit ddfd34a346aa7edcb572467da10ce319ae31c97b
52 changes: 31 additions & 21 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,9 @@ def visit_instance(self, template: Instance) 8000 -> List[Constraint]:
suffix.arg_kinds[len(prefix.arg_kinds):],
suffix.arg_names[len(prefix.arg_names):])
res.append(Constraint(mapped_arg.id, SUPERTYPE_OF, suffix))
elif isinstance(suffix, ParamSpecType):
res.append(Constraint(mapped_arg.id, SUPERTYPE_OF, suffix))

return res
elif (self.direction == SUPERTYPE_OF and
instance.type.has_base(template.type.fullname)):
Expand Down Expand Up @@ -496,6 +499,8 @@ def visit_instance(self, template: Instance) -> List[Constraint]:
suffix.arg_kinds[len(prefix.arg_kinds):],
suffix.arg_names[len(prefix.arg_names):])
res.append(Constraint(template_arg.id, SUPERTYPE_OF, suffix))
elif isinstance(suffix, ParamSpecType):
res.append(Constraint(template_arg.id, SUPERTYPE_OF, suffix))
return res
if (template.type.is_protocol and self.direction == SUPERTYPE_OF and
# We avoid infinite recursion for structural subtypes by checking
Expand Down Expand Up @@ -586,27 +591,32 @@ def visit_callable_type(self, template: CallableType) -> List[Constraint]:
# Negate direction due to function argument type contravariance.
res.extend(infer_constraints(t, a, neg_op(self.direction)))
else:
# TODO: Direction
# TODO: check the prefixes match
prefix = param_spec.prefix
prefix_len = len(prefix.arg_types)
res.append(Constraint(param_spec.id,
SUBTYPE_OF,
cactual.copy_modified(
arg_types=cactual.arg_types[prefix_len:],
arg_kinds=cactual.arg_kinds[prefix_len:],
arg_names=cactual.arg_names[prefix_len:],
ret_type=NoneType())))
# compare prefixes
cactual_prefix = cactual.copy_modified(
arg_types=cactual.arg_types[:prefix_len],
arg_kinds=cactual.arg_kinds[:prefix_len],
arg_names=cactual.arg_names[:prefix_len])

# TODO: see above "FIX" comments for param_spec is None case
# TODO: this assume positional arguments
for t, a in zip(prefix.arg_types, cactual_prefix.arg_types):
res.extend(infer_constraints(t, a, neg_op(self.direction)))
# sometimes, it appears we try to get constraints between two paramspec callables?
cactual_ps = cactual.param_spec()
if cactual_ps:
res.append(Constraint(param_spec.id, SUBTYPE_OF, cactual_ps))
else:
# TODO: Direction
# TODO: check the prefixes match
prefix = param_spec.prefix
prefix_len = len(prefix.arg_types)
res.append(Constraint(param_spec.id,
SUBTYPE_OF,
cactual.copy_modified(
arg_types=cactual.arg_types[prefix_len:],
arg_kinds=cactual.arg_kinds[prefix_len:],
arg_names=cactual.arg_names[prefix_len:],
ret_type=NoneType())))
# compare prefixes
cactual_prefix = cactual.copy_modified(
arg_types=cactual.arg_types[:prefix_len],
arg_kinds=cactual.arg_kinds[:prefix_len],
arg_names=cactual.arg_names[:prefix_len])

# TODO: see above "FIX" comments for param_spec is None case
# TODO: this assume positional arguments
for t, a in zip(prefix.arg_types, cactual_prefix.arg_types):
res.extend(infer_constraints(t, a, neg_op(self.direction)))

template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type
if template.type_guard is not None:
Expand Down
10 changes: 1 addition & 9 deletions mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1031,18 +1031,10 @@ def serialize(self) -> JsonDict:
@classmethod
def deserialize(self, data: JsonDict) -> 'ClassDef':
assert data['.class'] == 'ClassDef'

tvs_ = [mypy.types.deserialize_type(v) for v in data['type_vars']]
tvs = []
for tv in tvs_:
# mypy tells me to expand `tv`, which isn't necessary I believe?
assert isinstance(tv, mypy.types.TypeVarLikeType) # type: ignore[misc]
tvs.append(tv)

res = ClassDef(data['name'],
Block([]),
# https://github.com/python/mypy/issues/12257
tvs,
[cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v)) for v in data['type_vars']],
)
res.fullname = data['fullname']
return res
Expand Down
11 changes: 9 additions & 2 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1653,16 +1653,23 @@ def param_spec(self) -> Optional[ParamSpecType]:
def expand_param_spec(self,
c: Union['CallableType', Parameters],
no_prefix: bool = False) -> 'CallableType':
if isinstance(c, CallableType):
variables = c.variables
else:
variables = []

if no_prefix:
return self.copy_modified(arg_types=c.arg_types,
arg_kinds=c.arg_kinds,
arg_names=c.arg_names,
is_ellipsis_args=c.is_ellipsis_args)
is_ellipsis_args=c.is_ellipsis_args,
variables=variables + self.variables)
else:
return self.copy_modified(arg_types=self.arg_types[:-2] + c.arg_types,
arg_kinds=self.arg_kinds[:-2] + c.arg_kinds,
arg_names=self.arg_names[:-2] + c.arg_names,
is_ellipsis_args=c.is_ellipsis_args)
is_ellipsis_args=c.is_ellipsis_args,
variables=variables + self.variables)

def __hash__(self) -> int:
return hash((self.ret_type, self.is_type_obj(),
Expand Down
65 changes: 65 additions & 0 deletions test-data/unit/check-parameter-specification.test
Original file line number Diff line number Diff line change
Expand Up @@ -817,3 +817,68 @@ reveal_type(A().func(f, 42)) # N: Revealed type is "builtins.int*"
# TODO: this should reveal `int`
reveal_type(A().func(lambda x: x + x, 42)) # N: Revealed type is "Any"
[builtins fixtures/tuple.pyi]

[case testParamSpecConstraintOnOtherParamSpec]
from typing import Callable, TypeVar, Any, Generic
from typing_extensions import ParamSpec

CallableT = TypeVar("CallableT", bound=Callable[..., Any])
_P = ParamSpec("_P")
_R_co = TypeVar("_R_co", covariant=True)

def simple_decorator(callable: CallableT) -> CallableT:
...

class Job(Generic[_P, _R_co]):
def __init__(self, target: Callable[_P, _R_co]) -> None:
...


class A:
@simple_decorator
def func(self, action: Job[_P, None]) -> Job[_P, None]:
...

reveal_type(A.func) # N: Revealed type is "def [_P] (self: __main__.A, action: __main__.Job[_P`-1, None]) -> __main__.Job[_P`-1, None]"
reveal_type(A().func) # N: Revealed type is "def [_P] (action: __main__.Job[_P`4, None]) -> __main__.Job[_P`4, None]"
reveal_type(A().func(Job(lambda x: x))) # N: Revealed type is "__main__.Job[def (x: Any), None]"

def f(x: int, y: int) -> None: ...
reveal_type(A().func(Job(f))) # N: Revealed type is "__main__.Job[def (x: builtins.int, y: builtins.int), None]"
[builtins fixtures/tuple.pyi]

[case testConstraintBetweenParamSpecFunctions1]
from typing import Callable, TypeVar, Any, Generic
from typing_extensions import ParamSpec

_P = ParamSpec("_P")
_R_co = TypeVar("_R_co", covariant=True)

def simple_decorator(callable: Callable[_P, _R_co]) -> Callable[_P, _R_co]: ...
class Job(Generic[_P]): ...


@simple_decorator
def func(action: Job[_P], /) -> Callable[_P, None]:
...

reveal_type(func) # N: Revealed type is "def [_P] (__main__.Job[_P`-1]) -> def (*_P.args, **_P.kwargs)"
[builtins fixtures/tuple.pyi]

[case test 6DD9 ConstraintBetweenParamSpecFunctions2]
from typing import Callable, TypeVar, Any, Generic
from typing_extensions import ParamSpec

CallableT = TypeVar("CallableT", bound=Callable[..., Any])
_P = ParamSpec("_P")

def simple_decorator(callable: CallableT) -> CallableT: ...
class Job(Generic[_P]): ...


@simple_decorator
def func(action: Job[_P], /) -> Callable[_P, None]:
...

reveal_type(func) # N: Revealed type is "def [_P] (__main__.Job[_P`-1]) -> def (*_P.args, **_P.kwargs)"
[builtins fixtures/tuple.pyi]
0