Skip to content

Commit b969a55

Browse files
dmoissetddfisher
authored andcommitted
Fix + test for string format with %% and keys (#1908)
This fixes #1717 and adds the corresponding test.
1 parent e0b5893 commit b969a55

2 files changed

Lines changed: 8 additions & 1 deletion

File tree

mypy/checkstrformat.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,9 @@ def analyze_conversion_specifiers(self, specifiers: List[ConversionSpecifier],
8888
context: Context) -> bool:
8989
has_star = any(specifier.has_star() for specifier in specifiers)
9090
has_key = any(specifier.has_key() for specifier in specifiers)
91-
all_have_keys = all(specifier.has_key() for specifier in specifiers)
91+
all_have_keys = all(
92+
specifier.has_key() or specifier.type == '%' for specifier in specifiers
93+
)
9294

9395
if has_key and has_star:
9496
self.msg.string_interpolation_with_star_and_key(context)
@@ -145,6 +147,9 @@ def check_mapping_str_interpolation(self, specifiers: List[ConversionSpecifier],
145147
mapping[key_str] = self.accept(v)
146148

147149
for specifier in specifiers:
150+
if specifier.type == '%':
151+
# %% is allowed in mappings, no checking is required
152+
continue
148153
if specifier.key not in mapping:
149154
self.msg.key_not_in_mapping(specifier.key, replacements)
150155
return

test-data/unit/check-expressions.test

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -989,6 +989,8 @@ a = None # type: Any
989989
'%()d' % {'': 2}
990990
'%(a)d' % {'a': 1, 'b': 2, 'c': 3}
991991
'%(q)d' % {'a': 1, 'b': 2, 'c': 3} # E: Key 'q' not found in mapping
992+
'%(a)d %%' % {'a': 1}
993+
992994
[builtins fixtures/dict.py]
993995

994996
[case testStringInterpolationMappingDictTypes]

0 commit comments

Comments
 (0)