Debian Codegraph @

test-data/unit/check-formatting.test

raw
1
2 -- String interpolation
3 -- --------------------
4
5 [case testStringInterpolationType]
6 from typing import Tuple
7 i: int
8 f: float
9 s: str
10 t: Tuple[int]
11 '%d' % i
12 '%f' % f
13 '%s' % s
14 '%d' % (f,)
15 '%d' % (s,) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsInt")
16 '%d' % t
17 '%d' % s # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsInt")
18 '%f' % s # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsFloat")
19 '%x' % f # E: Incompatible types in string interpolation (expression has type "float", placeholder has type "int")
20 '%i' % f
21 '%o' % f # E: Incompatible types in string interpolation (expression has type "float", placeholder has type "int")
22 [builtins fixtures/primitives.pyi]
23 [typing fixtures/typing-medium.pyi]
24
25 [case testStringInterpolationSAcceptsAnyType]
26 from typing import Any
27 i: int
28 o: object
29 s: str
30 '%s %s %s' % (i, o, s)
31 [builtins fixtures/primitives.pyi]
32
33 [case testStringInterpolationSBytesVsStrErrorPy3]
34 xb: bytes
35 xs: str
36
37 '%s' % xs # OK
38 '%s' % xb # E: If x = b'abc' then "%s" % x produces "b'abc'", not "abc". If this is desired behavior use "%r" % x. Otherwise, decode the bytes
39 '%(name)s' % {'name': b'value'} # E: If x = b'abc' then "%s" % x produces "b'abc'", not "abc". If this is desired behavior use "%r" % x. Otherwise, decode the bytes
40 [builtins fixtures/primitives.pyi]
41
42 [case testStringInterpolationCount]
43 '%d %d' % 1 # E: Not enough arguments for format string
44 '%d %d' % (1, 2)
45 '%d %d' % (1, 2, 3) # E: Not all arguments converted during string formatting
46 t = 1, 's'
47 '%d %s' % t
48 '%s %d' % t # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsInt")
49 '%d' % t # E: Not all arguments converted during string formatting
50 [builtins fixtures/primitives.pyi]
51 [typing fixtures/typing-medium.pyi]
52
53 [case testStringInterpolationWithAnyType]
54 from typing import Any
55 a = None # type: Any
56 '%d %d' % a
57 [builtins fixtures/primitives.pyi]
58 [typing fixtures/typing-medium.pyi]
59
60 [case testStringInterpolationInvalidPlaceholder]
61 '%W' % 1 # E: Unsupported format character "W"
62 '%b' % 1 # E: Format character "b" is only supported on bytes patterns
63 '%(a)' % {'a': 1} # E: Unsupported format character ""
64
65 [case testStringInterpolationWidth]
66 '%2f' % 3.14
67 '%*f' % 3.14 # E: Not enough arguments for format string
68 '%*f' % (4, 3.14)
69 '%*f' % (1.1, 3.14) # E: * wants int
70 [builtins fixtures/primitives.pyi]
71 [typing fixtures/typing-medium.pyi]
72
73 [case testStringInterpolationPrecision]
74 '%.2f' % 3.14
75 '%.*f' % 3.14 # E: Not enough arguments for format string
76 '%.*f' % (4, 3.14)
77 '%.*f' % (1.1, 3.14) # E: * wants int
78 [builtins fixtures/primitives.pyi]
79 [typing fixtures/typing-medium.pyi]
80
81 [case testStringInterpolationWidthAndPrecision]
82 '%4.2f' % 3.14
83 '%4.*f' % 3.14 # E: Not enough arguments for format string
84 '%*.2f' % 3.14 # E: Not enough arguments for format string
85 '%*.*f' % 3.14 # E: Not enough arguments for format string
86 '%*.*f' % (4, 2, 3.14)
87 [builtins fixtures/primitives.pyi]
88 [typing fixtures/typing-medium.pyi]
89
90 [case testStringInterpolationFlagsAndLengthModifiers]
91 '%04hd' % 1
92 '%-.4ld' % 1
93 '%+*Ld' % (1, 1)
94 '% .*ld' % (1, 1)
95 [builtins fixtures/primitives.pyi]
96 [typing fixtures/typing-medium.pyi]
97
98 [case testStringInterpolationDoublePercentage]
99 '%% %d' % 1
100 '%3% %d' % 1
101 '%*%' % 1
102 '%*% %d' % 1 # E: Not enough arguments for format string
103 [builtins fixtures/primitives.pyi]
104 [typing fixtures/typing-medium.pyi]
105
106 [case testStringInterpolationC]
107 '%c' % 1
108 '%c' % 1.0 # E: "%c" requires int or char (expression has type "float")
109 '%c' % 's'
110 '%c' % '' # E: "%c" requires int or char
111 '%c' % 'ab' # E: "%c" requires int or char
112 '%c' % b'a' # E: "%c" requires int or char (expression has type "bytes")
113 '%c' % b'' # E: "%c" requires int or char (expression has type "bytes")
114 '%c' % b'ab' # E: "%c" requires int or char (expression has type "bytes")
115 [builtins fixtures/primitives.pyi]
116
117 [case testStringInterpolationMappingTypes]
118 '%(a)d %(b)s' % {'a': 1, 'b': 's'}
119 '%(a)d %(b)s' % {'a': 's', 'b': 1} # E: Incompatible types in string interpolation (expression has type "str", placeholder with key 'a' has type "int | float | SupportsInt")
120 b'%(x)s' % {b'x': b'data'}
121 [builtins fixtures/primitives.pyi]
122 [typing fixtures/typing-medium.pyi]
123
124 [case testStringInterpolationMappingKeys]
125 '%()d' % {'': 2}
126 '%(a)d' % {'a': 1, 'b': 2, 'c': 3}
127 '%(q)d' % {'a': 1, 'b': 2, 'c': 3} # E: Key "q" not found in mapping
128 '%(a)d %%' % {'a': 1}
129 [builtins fixtures/primitives.pyi]
130 [typing fixtures/typing-medium.pyi]
131
132 [case testStringInterpolationMappingDictTypes]
133 from typing import Any, Dict, Iterable
134
135 class StringThing:
136 def keys(self) -> Iterable[str]:
137 ...
138 def __getitem__(self, __key: str) -> str:
139 ...
140
141 class BytesThing:
142 def keys(self) -> Iterable[bytes]:
143 ...
144 def __getitem__(self, __key: bytes) -> str:
145 ...
146
147 a: Any
148 ds: Dict[str, int]
149 do: Dict[object, int]
150 di: Dict[int, int]
151 '%(a)' % 1 # E: Format requires a mapping (expression has type "int", expected type for mapping is "SupportsKeysAndGetItem[str, Any]")
152 '%()d' % a
153 '%()d' % ds
154 '%()d' % do # E: Format requires a mapping (expression has type "dict[object, int]", expected type for mapping is "SupportsKeysAndGetItem[str, Any]")
155 b'%()d' % ds # E: Format requires a mapping (expression has type "dict[str, int]", expected type for mapping is "SupportsKeysAndGetItem[bytes, Any]")
156 '%()s' % StringThing()
157 b'%()s' % BytesThing()
158 [builtins fixtures/primitives.pyi]
159
160 [case testStringInterpolationMappingInvalidSpecifiers]
161 '%(a)d %d' % 1 # E: String interpolation mixes specifier with and without mapping keys
162 '%(b)*d' % 1 # E: String interpolation contains both stars and mapping keys
163 '%(b).*d' % 1 # E: String interpolation contains both stars and mapping keys
164
165 [case testStringInterpolationMappingFlagsAndLengthModifiers]
166 '%(a)1d' % {'a': 1}
167 '%(a).1d' % {'a': 1}
168 '%(a)#1.1ld' % {'a': 1}
169 [builtins fixtures/primitives.pyi]
170 [typing fixtures/typing-medium.pyi]
171
172 [case testStringInterpolationFloatPrecision]
173 '%.f' % 1.2
174 '%.3f' % 1.2
175 '%.f' % 'x'
176 '%.3f' % 'x'
177 [builtins fixtures/primitives.pyi]
178 [typing fixtures/typing-medium.pyi]
179 [out]
180 main:3: error: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsFloat")
181 main:4: error: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsFloat")
182
183 [case testStringInterpolationSpaceKey]
184 '%( )s' % {' ': 'foo'}
185
186 [case testStringInterpolationStarArgs]
187 x = (1, 2)
188 "%d%d" % (*x,)
189 [typing fixtures/typing-medium.pyi]
190 [builtins fixtures/tuple.pyi]
191
192 [case testStringInterpolationVariableLengthTuple]
193 from typing import Tuple
194 def f(t: Tuple[int, ...]) -> None:
195 '%d %d' % t
196 '%d %d %d' % t
197 [builtins fixtures/primitives.pyi]
198 [typing fixtures/typing-medium.pyi]
199
200 [case testStringInterpolationUnionType]
201 from typing import Tuple, Union
202 a: Union[Tuple[int, str], Tuple[str, int]] = ('A', 1)
203 '%s %s' % a
204 '%s' % a # E: Not all arguments converted during string formatting
205
206 b: Union[Tuple[int, str], Tuple[int, int], Tuple[str, int]] = ('A', 1)
207 '%s %s' % b
208 '%s %s %s' % b # E: Not enough arguments for format string
209
210 c: Union[Tuple[str, int], Tuple[str, int, str]] = ('A', 1)
211 '%s %s' % c # E: Not all arguments converted during string formatting
212 [builtins fixtures/tuple.pyi]
213
214 [case testStringInterpolationIterableType]
215 from typing import Sequence, List, Tuple, Iterable
216
217 t1: Sequence[str] = ('A', 'B')
218 t2: List[str] = ['A', 'B']
219 t3: Tuple[str, ...] = ('A', 'B')
220 t4: Tuple[str, str] = ('A', 'B')
221 t5: Iterable[str] = ('A', 'B')
222 '%s %s' % t1
223 '%s %s' % t2
224 '%s %s' % t3
225 '%s %s %s' % t3
226 '%s %s' % t4
227 '%s %s %s' % t4 # E: Not enough arguments for format string
228 '%s %s' % t5
229 [builtins fixtures/tuple.pyi]
230
231
232 -- Bytes interpolation
233 -- --------------------
234
235 [case testBytesInterpolation]
236 b'%b' % 1 # E: Incompatible types in string interpolation (expression has type "int", placeholder has type "bytes")
237 b'%b' % b'1'
238 b'%a' % 3
239
240 [case testBytesInterpolationC]
241 b'%c' % 1
242 b'%c' % 1.0 # E: "%c" requires an integer in range(256) or a single byte (expression has type "float")
243 b'%c' % 's' # E: "%c" requires an integer in range(256) or a single byte (expression has type "str")
244 b'%c' % '' # E: "%c" requires an integer in range(256) or a single byte (expression has type "str")
245 b'%c' % 'ab' # E: "%c" requires an integer in range(256) or a single byte (expression has type "str")
246 b'%c' % b'a'
247 b'%c' % b'' # E: "%c" requires an integer in range(256) or a single byte
248 b'%c' % b'aa' # E: "%c" requires an integer in range(256) or a single byte
249 [builtins fixtures/primitives.pyi]
250
251 [case testByteByteInterpolation]
252 def foo(a: bytes, b: bytes):
253 b'%s:%s' % (a, b)
254 foo(b'a', b'b') == b'a:b'
255 [builtins fixtures/tuple.pyi]
256
257 [case testBytePercentInterpolationSupported]
258 b'%s' % (b'xyz',)
259 b'%(name)s' % {'name': b'jane'} # E: Dictionary keys in bytes formatting must be bytes, not strings
260 b'%(name)s' % {b'name': 'jane'} # E: On Python 3 b'%s' requires bytes, not string
261 b'%c' % (123)
262 [builtins fixtures/tuple.pyi]
263
264
265 -- str.format() calls
266 -- ------------------
267
268
269 [case testFormatCallParseErrors]
270 '}'.format() # E: Invalid conversion specifier in format string: unexpected }
271 '{'.format() # E: Invalid conversion specifier in format string: unmatched {
272
273 '}}'.format() # OK
274 '{{'.format() # OK
275
276 '{{}}}'.format() # E: Invalid conversion specifier in format string: unexpected }
277 '{{{}}'.format() # E: Invalid conversion specifier in format string: unexpected }
278
279 '{}}{{}'.format() # E: Invalid conversion specifier in format string: unexpected }
280 '{{{}:{}}}'.format(0) # E: Cannot find replacement for positional format specifier 1
281 [builtins fixtures/primitives.pyi]
282
283 [case testFormatCallValidationErrors]
284 '{!}}'.format(0) # E: Invalid conversion specifier in format string: unexpected }
285 '{!x}'.format(0) # E: Invalid conversion type "x", must be one of "r", "s" or "a"
286 '{!:}'.format(0) # E: Invalid conversion specifier in format string
287
288 '{{}:s}'.format(0) # E: Invalid conversion specifier in format string: unexpected }
289 '{{}.attr}'.format(0) # E: Invalid conversion specifier in format string: unexpected }
290 '{{}[key]}'.format(0) # E: Invalid conversion specifier in format string: unexpected }
291
292 '{ {}:s}'.format() # E: Conversion value must not contain { or }
293 '{ {}.attr}'.format() # E: Conversion value must not contain { or }
294 '{ {}[key]}'.format() # E: Conversion value must not contain { or }
295 [builtins fixtures/primitives.pyi]
296
297 [case testFormatCallEscaping]
298 '{}'.format() # E: Cannot find replacement for positional format specifier 0
299 '{}'.format(0) # OK
300
301 '{{}}'.format() # OK
302 '{{}}'.format(0) # E: Not all arguments converted during string formatting
303
304 '{{{}}}'.format() # E: Cannot find replacement for positional format specifier 0
305 '{{{}}}'.format(0) # OK
306
307 '{{}} {} {{}}'.format(0) # OK
308 '{{}} {:d} {{}} {:d}'.format('a', 'b') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
309
310 'foo({}, {}) == {{}} ({{}} expected)'.format(0) # E: Cannot find replacement for positional format specifier 1
311 'foo({}, {}) == {{}} ({{}} expected)'.format(0, 1) # OK
312 'foo({}, {}) == {{}} ({{}} expected)'.format(0, 1, 2) # E: Not all arguments converted during string formatting
313 [builtins fixtures/primitives.pyi]
314
315 [case testFormatCallNestedFormats]
316 '{:{}{}}'.format(42, '*') # E: Cannot find replacement for positional format specifier 2
317 '{:{}{}}'.format(42, '*', '^') # OK
318 '{:{}{}}'.format(42, '*', '^', 0) # E: Not all arguments converted during string formatting
319
320 # NOTE: we don't check format specifiers that contain { or } at all
321 '{:{{}}}'.format() # E: Cannot find replacement for positional format specifier 0
322
323 '{:{:{}}}'.format() # E: Formatting nesting must be at most two levels deep
324 '{:{{}:{}}}'.format() # E: Invalid conversion specifier in format string: unexpected }
325
326 '{!s:{fill:d}{align}}'.format(42, fill='*', align='^') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
327 [builtins fixtures/primitives.pyi]
328
329 [case testFormatCallAutoNumbering]
330 '{}, {{}}, {0}'.format() # E: Cannot combine automatic field numbering and manual field specification
331 '{0}, {1}, {}'.format() # E: Cannot combine automatic field numbering and manual field specification
332
333 '{0}, {1}, {0}'.format(1, 2, 3) # E: Not all arguments converted during string formatting
334 '{}, {other:+d}, {}'.format(1, 2, other='no') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
335 '{0}, {other}, {}'.format() # E: Cannot combine automatic field numbering and manual field specification
336
337 '{:{}}, {:{:.5d}{}}'.format(1, 2, 3, 'a', 5) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
338 [builtins fixtures/primitives.pyi]
339
340 [case testFormatCallMatchingPositional]
341 '{}'.format(positional='no') # E: Cannot find replacement for positional format specifier 0 \
342 # E: Not all arguments converted during string formatting
343 '{.x}, {}, {}'.format(1, 'two', 'three') # E: "int" has no attribute "x"
344 'Reverse {2.x}, {1}, {0}'.format(1, 2, 'three') # E: "str" has no attribute "x"
345 ''.format(1, 2) # E: Not all arguments converted during string formatting
346 [builtins fixtures/primitives.pyi]
347
348 [case testFormatCallMatchingNamed]
349 '{named}'.format(0) # E: Cannot find replacement for named format specifier "named" \
350 # E: Not all arguments converted during string formatting
351 '{one.x}, {two}'.format(one=1, two='two') # E: "int" has no attribute "x"
352 '{one}, {two}, {.x}'.format(1, one='two', two='three') # E: "int" has no attribute "x"
353 ''.format(stuff='yes') # E: Not all arguments converted during string formatting
354 [builtins fixtures/primitives.pyi]
355
356 [case testFormatCallMatchingVarArg]
357 from typing import List
358 args: List[int] = []
359 '{}, {}'.format(1, 2, *args) # Don't flag this because args may be empty
360
361 strings: List[str]
362 '{:d}, {[0].x}'.format(*strings) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int") \
363 # E: "str" has no attribute "x"
364 # TODO: this is a runtime error, but error message is confusing
365 '{[0][:]:d}'.format(*strings) # E: Syntax error in format specifier "0[0]["
366 [builtins fixtures/primitives.pyi]
367
368 [case testFormatCallMatchingKwArg]
369 from typing import Dict
370 kwargs: Dict[str, str] = {}
371 '{one}, {two}'.format(one=1, two=2, **kwargs) # Don't flag this because args may be empty
372
373 '{stuff:.3d}'.format(**kwargs) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
374 '{stuff[0]:f}, {other}'.format(**kwargs) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float")
375 '{stuff[0]:c}'.format(**kwargs)
376 [builtins fixtures/primitives.pyi]
377
378 [case testFormatCallCustomFormatSpec]
379 from typing import Union
380 class Bad:
381 ...
382 class Good:
383 def __format__(self, spec: str) -> str: ...
384
385 '{:OMG}'.format(Good())
386 '{:OMG}'.format(Bad()) # E: Unrecognized format specification "OMG"
387 '{!s:OMG}'.format(Good()) # E: Unrecognized format specification "OMG"
388 '{:{}OMG{}}'.format(Bad(), 'too', 'dynamic')
389
390 x: Union[Good, Bad]
391 '{:OMG}'.format(x) # E: Unrecognized format specification "OMG"
392 [builtins fixtures/primitives.pyi]
393
394 [case testFormatCallFormatTypes]
395 '{:x}'.format(42)
396 '{:E}'.format(42)
397 '{:g}'.format(42)
398 '{:x}'.format('no') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
399 '{:E}'.format('no') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float")
400 '{:g}'.format('no') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float")
401 '{:n}'.format(3.14)
402 '{:d}'.format(3.14) # E: Incompatible types in string interpolation (expression has type "float", placeholder has type "int")
403
404 '{:s}'.format(42)
405 '{:s}'.format('yes')
406
407 '{:z}'.format('what') # E: Unsupported format character "z"
408 '{:Z}'.format('what') # E: Unsupported format character "Z"
409 [builtins fixtures/primitives.pyi]
410
411 [case testFormatCallFormatTypesChar]
412 '{:c}'.format(42)
413 '{:c}'.format('no') # E: ":c" requires int or char
414 '{:c}'.format('c')
415
416 class C:
417 ...
418 '{:c}'.format(C()) # E: Incompatible types in string interpolation (expression has type "C", placeholder has type "int | str")
419 x: str
420 '{:c}'.format(x)
421 [builtins fixtures/primitives.pyi]
422
423 [case testFormatCallFormatTypesCustomFormat]
424 from typing import Union
425 class Bad:
426 ...
427 class Good:
428 def __format__(self, spec: str) -> str: ...
429
430 x: Union[Good, Bad]
431 y: Union[Good, int]
432 z: Union[Bad, int]
433 t: Union[Good, str]
434 '{:d}'.format(x) # E: Incompatible types in string interpolation (expression has type "Bad", placeholder has type "int")
435 '{:d}'.format(y)
436 '{:d}'.format(z) # E: Incompatible types in string interpolation (expression has type "Bad", placeholder has type "int")
437 '{:d}'.format(t) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
438 [builtins fixtures/primitives.pyi]
439
440 [case testFormatCallFormatTypesBytes]
441 from typing import Union, TypeVar, NewType, Generic
442
443 A = TypeVar('A', str, bytes)
444 B = TypeVar('B', bound=bytes)
445
446 x: Union[str, bytes]
447 a: str
448 b: bytes
449
450 N = NewType('N', bytes)
451 n: N
452
453 '{}'.format(a)
454 '{}'.format(b) # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
455 '{}'.format(x) # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
456 '{}'.format(n) # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
457
458 f'{b}' # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
459 f'{x}' # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
460 f'{n}' # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
461
462 class C(Generic[B]):
463 x: B
464 def meth(self) -> None:
465 '{}'.format(self.x) # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
466
467 def func(x: A) -> A:
468 '{}'.format(x) # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes
469 return x
470
471 '{!r}'.format(a)
472 '{!r}'.format(b)
473 '{!r}'.format(x)
474 '{!r}'.format(n)
475 f'{a}'
476 f'{a!r}'
477 f'{b!r}'
478 f'{x!r}'
479 f'{n!r}'
480
481 class D(bytes):
482 def __str__(self) -> str:
483 return "overrides __str__ of bytes"
484
485 '{}'.format(D())
486 [builtins fixtures/primitives.pyi]
487
488 [case testNoSpuriousFormattingErrorsDuringFailedOverlodMatch]
489 from typing import overload, Callable
490
491 @overload
492 def sub(pattern: str, repl: Callable[[str], str]) -> str: ...
493 @overload
494 def sub(pattern: bytes, repl: Callable[[bytes], bytes]) -> bytes: ...
495 def sub(pattern: object, repl: object) -> object:
496 pass
497
498 def better_snakecase(text: str) -> str:
499 # Mypy used to emit a spurious error here
500 # warning about interpolating bytes into an f-string:
501 text = sub(r"([A-Z])([A-Z]+)([A-Z](?:[^A-Z]|$))", lambda match: f"{match}")
502 return text
503 [builtins fixtures/primitives.pyi]
504
505 [case testFormatCallFinal]
506 from typing import Final
507
508 FMT: Final = '{.x}, {:{:d}}'
509
510 FMT.format(1, 2, 'no') # E: "int" has no attribute "x" \
511 # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
512 [builtins fixtures/primitives.pyi]
513
514 [case testFormatCallFinalChar]
515 from typing import Final
516
517 GOOD: Final = 'c'
518 BAD: Final = 'no'
519 OK: Final[str] = '...'
520
521 '{:c}'.format(GOOD)
522 '{:c}'.format(BAD) # E: ":c" requires int or char
523 '{:c}'.format(OK)
524 [builtins fixtures/primitives.pyi]
525
526 [case testFormatCallForcedConversions]
527 '{!r}'.format(42)
528 '{!s}'.format(42)
529 '{!s:d}'.format(42) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int")
530 '{!s:s}'.format('OK')
531 '{} and {!x}'.format(0, 1) # E: Invalid conversion type "x", must be one of "r", "s" or "a"
532 [builtins fixtures/primitives.pyi]
533
534 [case testFormatCallAccessorsBasic]
535 from typing import Any
536 x: Any
537
538 '{.x:{[0]}}'.format('yes', 42) # E: "str" has no attribute "x" \
539 # E: Value of type "int" is not indexable
540
541 '{.1+}'.format(x) # E: Syntax error in format specifier "0.1+"
542 '{name.x[x]()[x]:.2f}'.format(name=x) # E: Only index and member expressions are allowed in format field accessors; got "name.x[x]()[x]"
543 [builtins fixtures/primitives.pyi]
544
545 [case testFormatCallAccessorsIndices]
546 from typing import TypedDict
547
548 class User(TypedDict):
549 id: int
550 name: str
551
552 u: User
553 '{user[name]:.3f}'.format(user=u) # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float")
554
555 def f() -> str: ...
556 '{[f()]}'.format(u) # E: Invalid index expression in format field accessor "[f()]"
557 [builtins fixtures/primitives.pyi]
558 [typing fixtures/typing-typeddict.pyi]
559
560 [case testFormatCallFlags]
561 from typing import Union
562
563 class Good:
564 def __format__(self, spec: str) -> str: ...
565
566 '{:#}'.format(42)
567
568 '{:#}'.format('no') # E: Numeric flags are only allowed for numeric types
569 '{!s:#}'.format(42) # E: Numeric flags are only allowed for numeric types
570
571 '{:#s}'.format(42) # E: Numeric flags are only allowed for numeric types
572 '{:+s}'.format(42) # E: Numeric flags are only allowed for numeric types
573
574 '{:+d}'.format(42)
575 '{:#d}'.format(42)
576
577 x: Union[float, Good]
578 '{:+f}'.format(x)
579 [builtins fixtures/primitives.pyi]
580 [typing fixtures/typing-medium.pyi]
581
582 [case testFormatCallSpecialCases]
583 '{:08b}'.format(int('3'))
584
585 class S:
586 def __int__(self) -> int: ...
587
588 '{:+d}'.format(S()) # E: Incompatible types in string interpolation (expression has type "S", placeholder has type "int")
589 '%d' % S() # This is OK however
590 '{:%}'.format(0.001)
591 [builtins fixtures/primitives.pyi]
592 [typing fixtures/typing-medium.pyi]
593
594 [case testEnumWithStringToFormatValue]
595 from enum import Enum
596
597 class Responses(str, Enum):
598 TEMPLATED = 'insert {} here'
599 TEMPLATED_WITH_KW = 'insert {value} here'
600 NORMAL = 'something'
601
602 Responses.TEMPLATED.format(42)
603 Responses.TEMPLATED_WITH_KW.format(value=42)
604 Responses.TEMPLATED.format() # E: Cannot find replacement for positional format specifier 0
605 Responses.TEMPLATED_WITH_KW.format() # E: Cannot find replacement for named format specifier "value"
606 Responses.NORMAL.format(42) # E: Not all arguments converted during string formatting
607 Responses.NORMAL.format(value=42) # E: Not all arguments converted during string formatting
608 [builtins fixtures/primitives.pyi]
609
610 [case testNonStringEnumToFormatValue]
611 from enum import Enum
612
613 class Responses(Enum):
614 TEMPLATED = 'insert {value} here'
615
616 Responses.TEMPLATED.format(value=42) # E: "Responses" has no attribute "format"
617 [builtins fixtures/primitives.pyi]
618
619 [case testStrEnumWithStringToFormatValue]
620 # flags: --python-version 3.11
621 from enum import StrEnum
622
623 class Responses(StrEnum):
624 TEMPLATED = 'insert {} here'
625 TEMPLATED_WITH_KW = 'insert {value} here'
626 NORMAL = 'something'
627
628 Responses.TEMPLATED.format(42)
629 Responses.TEMPLATED_WITH_KW.format(value=42)
630 Responses.TEMPLATED.format() # E: Cannot find replacement for positional format specifier 0
631 Responses.TEMPLATED_WITH_KW.format() # E: Cannot find replacement for named format specifier "value"
632 Responses.NORMAL.format(42) # E: Not all arguments converted during string formatting
633 Responses.NORMAL.format(value=42) # E: Not all arguments converted during string formatting
634 [builtins fixtures/primitives.pyi]
635
636 [case testDebugFStringReprAutoApplied]
637 test = b"abc"
638 debug = f"{test=}" # OK, no str/bytes warning since !r is implicit
639 [builtins fixtures/primitives.pyi]