Return the type that is accepted for a string interpolation conversion specifier type. Note that both Python's float (e.g. %f) and integer (e.g. %d) specifier types accept both float and integers. The 'format_call' argument indicates whether this type came from % interpolat
(
self, p: str, context: Context, expr: FormatStringExpr, format_call: bool = False
)
| 1016 | return check_expr, check_type |
| 1017 | |
| 1018 | def conversion_type( |
| 1019 | self, p: str, context: Context, expr: FormatStringExpr, format_call: bool = False |
| 1020 | ) -> Type | None: |
| 1021 | """Return the type that is accepted for a string interpolation conversion specifier type. |
| 1022 | |
| 1023 | Note that both Python's float (e.g. %f) and integer (e.g. %d) |
| 1024 | specifier types accept both float and integers. |
| 1025 | |
| 1026 | The 'format_call' argument indicates whether this type came from % interpolation or from |
| 1027 | a str.format() call, the meaning of few formatting types are different. |
| 1028 | """ |
| 1029 | NUMERIC_TYPES = NUMERIC_TYPES_NEW if format_call else NUMERIC_TYPES_OLD |
| 1030 | INT_TYPES = REQUIRE_INT_NEW if format_call else REQUIRE_INT_OLD |
| 1031 | if p == "b" and not format_call: |
| 1032 | if not isinstance(expr, BytesExpr): |
| 1033 | self.msg.fail( |
| 1034 | 'Format character "b" is only supported on bytes patterns', |
| 1035 | context, |
| 1036 | code=codes.STRING_FORMATTING, |
| 1037 | ) |
| 1038 | return None |
| 1039 | return self.named_type("builtins.bytes") |
| 1040 | elif p == "a": |
| 1041 | # TODO: return type object? |
| 1042 | return AnyType(TypeOfAny.special_form) |
| 1043 | elif p in ["s", "r"]: |
| 1044 | return AnyType(TypeOfAny.special_form) |
| 1045 | elif p in NUMERIC_TYPES: |
| 1046 | if p in INT_TYPES: |
| 1047 | numeric_types = [self.named_type("builtins.int")] |
| 1048 | else: |
| 1049 | numeric_types = [ |
| 1050 | self.named_type("builtins.int"), |
| 1051 | self.named_type("builtins.float"), |
| 1052 | ] |
| 1053 | if not format_call: |
| 1054 | if p in FLOAT_TYPES: |
| 1055 | numeric_types.append(self.named_type("typing.SupportsFloat")) |
| 1056 | else: |
| 1057 | numeric_types.append(self.named_type("typing.SupportsInt")) |
| 1058 | return UnionType.make_union(numeric_types) |
| 1059 | elif p in ["c"]: |
| 1060 | if isinstance(expr, BytesExpr): |
| 1061 | return UnionType( |
| 1062 | [self.named_type("builtins.int"), self.named_type("builtins.bytes")] |
| 1063 | ) |
| 1064 | else: |
| 1065 | return UnionType( |
| 1066 | [self.named_type("builtins.int"), self.named_type("builtins.str")] |
| 1067 | ) |
| 1068 | else: |
| 1069 | self.msg.unsupported_placeholder(p, context) |
| 1070 | return None |
| 1071 | |
| 1072 | # |
| 1073 | # Helpers |
no test coverage detected