8000 Accept compatible dict in place of TypedDict by pkch · Pull Request #3035 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Accept compatible dict in place of TypedDict #3035

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 6 commits into from
Mar 31, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
Next Next commit
Accept compatible dict in place of TypedDict
  • Loading branch information
pkch committed Mar 20, 2017
commit 5bd90ea2ee538f77e8ff2c247ab6d053ffdcbcbf
7 changes: 7 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -1694,6 +1694,13 @@ def visit_dict_expr(self, e: DictExpr) -> Type:

Translate it into a call to dict(), with provisions for **expr.
"""
if isinstance(self.type_context[-1], TypedDictType):
return self.check_typeddict_call_with_dict(
callee=self.type_context[-1],
kwargs=e,
context=e
)

# Collect function arguments, watching out for **expr.
args = [] # type: List[Expression] # Regular "key: value"
stargs = [] # type: List[Expression] # For "**expr"
Expand Down
8 changes: 5 additions & 3 deletions mypy/test/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ def expand_errors(input: List[str], output: List[str], fnam: str) -> None:
# The first in the split things isn't a comment
for possible_err_comment in input[i].split('#')[1:]:
m = re.search(
'^([ENW]):((?P<col>\d+):)? (?P<message>.*)$',
'^([ENW]):((?P<col>\d+):)?((?P<backtrack>-\d+):)? (?P<message>.*)$',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer this as a separate PR, proposed syntax is debatable and could only delay this PR.

possible_err_comment.strip())
if m:
if m.group(1) == 'E':
Expand All @@ -389,12 +389,14 @@ def expand_errors(input: List[str], output: List[str], fnam: str) -> None:
elif m.group(1) == 'W':
severity = 'warning'
col = m.group('col')
backtrack = int(m.group('backtrack')) if m.group('backtrack') is not None else 0
if col is None:
output.append(
'{}:{}: {}: {}'.format(fnam, i + 1, severity, m.group('message')))
'{}:{}: {}: {}'.format(fnam, i + 1 + backtrack,
severity, m.group('message')))
else:
output.append('{}:{}:{}: {}: {}'.format(
fnam, i + 1, col, severity, m.group('message')))
fnam, i + 1 + backtrack, col, severity, m.group('message')))


def fix_win_path(line: str) -> str:
Expand Down
6 changes: 5 additions & 1 deletion test-data/unit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ Add the test in this format anywhere in the file:
- `# E: abc...` indicates that this line should result in type check error
with text "abc..."
- note a space after `E:` and `flags:`
- lines without `# E: ` should cause no type check errors
- `# E:12` adds column number to the expected error
- `# E:-1` means that the error was expected 2 lines ago (helpful for multiple errors in a line)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't you already do 4 = 3 # E: error one # E: error two?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JelleZijlstra Yup ;)
@ilevkivskyi One error is about TypedDict not matching the dict structure. But it then infers the wrong TypedDict anyway (to keep going), and that doesn't fit the function call. I can probably change it to make it one error, but it would require more logic elsewhere in the code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkch

but it would require more logic elsewhere in the code.

Yes.

- `# E:12:-1` combines the two options above
- `W: ...` and `N: ...` works exactly like `E:`, but report a warning and a note respectively
- lines that don't contain the above should cause no type check errors
- optional `[builtins fixtures/...]` tells the type checker to use
stubs from the indicated file (see Fixtures section below)
- optional `[out]` is an alternative to the "# E:" notation: it indicates that
Expand Down
23 changes: 23 additions & 0 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
8000 Expand Up @@ -610,3 +610,26 @@ def f() -> None:
A = TypedDict('A', {'x': int})
A # E: Name 'A' is not defined
[builtins fixtures/dict.pyi]


-- Use dict literals

[case testTypedDictDictLiterals]
from mypy_extensions import TypedDict

Point = TypedDict('Point', {'x': int, 'y': int})

def f(p: Point) -> None:
p = {'x': 2, 'y': 3}
p = {'x': 2} # E: Expected items ['x', 'y'] but found ['x'].
p = dict(x=2, y=3)

f({'x': 1, 'y': 3})
f({'x': 1, 'y': 'z'}) # E: Argument 1 to "f" has incompatible type "TypedDict(x=int, y=str)"; expected "Point"
# E:-1: Incompatible types (expression has type "str", TypedDict item "y" has type "int")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think only one of these error messages should be shown, not both.


f(dict(x=1, y=3))
f(dict(x=1, y=3, z=4)) # E: Expected items ['x', 'y'] but found ['x', 'y', 'z'].
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7CCB

I would add one more test case with few tests where you assign to variables with explicit types, like:

p: Point = {'x', 'hi'}

and/or

p: Point
p = dict(x='bye')

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also maybe a test for

p = Point(x=1, y=2)
p = {x='hi'}


[builtins fixtures/dict.pyi]

0