MCPcopy
hub / github.com/python/mypy / check_specs_in_format_call

Method check_specs_in_format_call

mypy/checkstrformat.py:333–404  ·  view source on GitHub ↗

Perform pairwise checks for conversion specifiers vs their replacements. The core logic for format checking is implemented in this method.

(
        self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str
    )

Source from the content-addressed store, hash-verified

331 self.check_specs_in_format_call(call, conv_specs, format_value)
332
333 def check_specs_in_format_call(
334 self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str
335 ) -> None:
336 """Perform pairwise checks for conversion specifiers vs their replacements.
337
338 The core logic for format checking is implemented in this method.
339 """
340 assert all(s.key for s in specs), "Keys must be auto-generated first!"
341 replacements = self.find_replacements_in_call(call, [cast(str, s.key) for s in specs])
342 assert len(replacements) == len(specs)
343 for spec, repl in zip(specs, replacements):
344 repl = self.apply_field_accessors(spec, repl, ctx=call)
345 actual_type = repl.type if isinstance(repl, TempNode) else self.chk.lookup_type(repl)
346 assert actual_type is not None
347
348 # Special case custom formatting.
349 if (
350 spec.format_spec
351 and spec.non_standard_format_spec
352 and
353 # Exclude "dynamic" specifiers (i.e. containing nested formatting).
354 not ("{" in spec.format_spec or "}" in spec.format_spec)
355 ):
356 if (
357 not custom_special_method(actual_type, "__format__", check_all=True)
358 or spec.conversion
359 ):
360 # TODO: add support for some custom specs like datetime?
361 self.msg.fail(
362 f'Unrecognized format specification "{spec.format_spec[1:]}"',
363 call,
364 code=codes.STRING_FORMATTING,
365 )
366 continue
367 # Adjust expected and actual types.
368 if not spec.conv_type:
369 expected_type: Type | None = AnyType(TypeOfAny.special_form)
370 else:
371 assert isinstance(call.callee, MemberExpr)
372 if isinstance(call.callee.expr, StrExpr):
373 format_str = call.callee.expr
374 else:
375 format_str = StrExpr(format_value)
376 expected_type = self.conversion_type(
377 spec.conv_type, call, format_str, format_call=True
378 )
379 if spec.conversion is not None:
380 # If the explicit conversion is given, then explicit conversion is called _first_.
381 if spec.conversion[1] not in "rsa":
382 self.msg.fail(
383 (
384 f'Invalid conversion type "{spec.conversion[1]}", '
385 f'must be one of "r", "s" or "a"'
386 ),
387 call,
388 code=codes.STRING_FORMATTING,
389 )
390 actual_type = self.named_type("builtins.str")

Callers 1

check_str_format_callMethod · 0.95

Calls 15

apply_field_accessorsMethod · 0.95
conversion_typeMethod · 0.95
named_typeMethod · 0.95
custom_special_methodFunction · 0.90
AnyTypeClass · 0.90
StrExprClass · 0.90
get_proper_typeFunction · 0.90
get_proper_typesFunction · 0.90
allFunction · 0.85

Tested by

no test coverage detected