Skip to content

Commit 9bd6517

Browse files
Use lookup_fully_qualified for SemanticAnalyzer.named_type (#11332)
Related to #6578 This PR replaces lookup_qualified with lookup_fully_qualified for SemanticAnalyzer.named_type. Now it's consistant with the implementation of checker.named_type. This change also allows calling named_type without dunders.
1 parent d807e09 commit 9bd6517

10 files changed

+34
-38
lines changed

mypy/plugin.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -250,13 +250,13 @@ class SemanticAnalyzerPluginInterface:
250250
msg: MessageBuilder
251251

252252
@abstractmethod
253-
def named_type(self, qualified_name: str, args: Optional[List[Type]] = None) -> Instance:
253+
def named_type(self, fullname: str,
254+
args: Optional[List[Type]] = None) -> Instance:
254255
"""Construct an instance of a builtin type with given type arguments."""
255256
raise NotImplementedError
256257

257258
@abstractmethod
258-
def named_type_or_none(self,
259-
qualified_name: str,
259+
def named_type_or_none(self, fullname: str,
260260
args: Optional[List[Type]] = None) -> Optional[Instance]:
261261
"""Construct an instance of a type with given type arguments.
262262

mypy/plugins/attrs.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -640,8 +640,8 @@ def _parse_assignments(
640640

641641
def _add_order(ctx: 'mypy.plugin.ClassDefContext', adder: 'MethodAdder') -> None:
642642
"""Generate all the ordering methods for this class."""
643-
bool_type = ctx.api.named_type('__builtins__.bool')
644-
object_type = ctx.api.named_type('__builtins__.object')
643+
bool_type = ctx.api.named_type('builtins.bool')
644+
object_type = ctx.api.named_type('builtins.object')
645645
# Make the types be:
646646
# AT = TypeVar('AT')
647647
# def __lt__(self: AT, other: AT) -> bool
@@ -714,7 +714,7 @@ def _add_attrs_magic_attribute(ctx: 'mypy.plugin.ClassDefContext',
714714
ctx.api.named_type_or_none('attr.Attribute', [attr_type or any_type]) or any_type
715715
for attr_type in raw_attr_types
716716
]
717-
fallback_type = ctx.api.named_type('__builtins__.tuple', [
717+
fallback_type = ctx.api.named_type('builtins.tuple', [
718718
ctx.api.named_type_or_none('attr.Attribute', [any_type]) or any_type,
719719
])
720720
var = Var(name=attr_name, type=TupleType(attributes_types, fallback=fallback_type))

mypy/plugins/common.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -122,13 +122,8 @@ def add_method_to_class(
122122
cls.defs.body.remove(sym.node)
123123

124124
self_type = self_type or fill_typevars(info)
125-
# TODO: semanal.py and checker.py seem to have subtly different implementations of
126-
# named_type/named_generic_type (starting with the fact that we have to use different names
127-
# for builtins), so it's easier to just check which one we're dealing with here and pick the
128-
# correct function to use than to try to add a named_type method that behaves the same for
129-
# both. We should probably combine those implementations at some point.
130125
if isinstance(api, SemanticAnalyzerPluginInterface):
131-
function_type = api.named_type('__builtins__.function')
126+
function_type = api.named_type('builtins.function')
132127
else:
133128
function_type = api.named_generic_type('builtins.function', [])
134129

mypy/plugins/dataclasses.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def transform(self) -> None:
145145
if (decorator_arguments['eq'] and info.get('__eq__') is None or
146146
decorator_arguments['order']):
147147
# Type variable for self types in generated methods.
148-
obj_type = ctx.api.named_type('__builtins__.object')
148+
obj_type = ctx.api.named_type('builtins.object')
149149
self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME,
150150
[], obj_type)
151151
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
@@ -158,10 +158,10 @@ def transform(self) -> None:
158158
for method_name in ['__lt__', '__gt__', '__le__', '__ge__']:
159159
# Like for __eq__ and __ne__, we want "other" to match
160160
# the self type.
161-
obj_type = ctx.api.named_type('__builtins__.object')
161+
obj_type = ctx.api.named_type('builtins.object')
162162
order_tvar_def = TypeVarType(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME,
163163
-1, [], obj_type)
164-
order_return_type = ctx.api.named_type('__builtins__.bool')
164+
order_return_type = ctx.api.named_type('builtins.bool')
165165
order_args = [
166166
Argument(Var('other', order_tvar_def), order_tvar_def, None, ARG_POS)
167167
]
@@ -426,8 +426,8 @@ def _add_dataclass_fields_magic_attribute(self) -> None:
426426
attr_name = '__dataclass_fields__'
427427
any_type = AnyType(TypeOfAny.explicit)
428428
field_type = self._ctx.api.named_type_or_none('dataclasses.Field', [any_type]) or any_type
429-
attr_type = self._ctx.api.named_type('__builtins__.dict', [
430-
self._ctx.api.named_type('__builtins__.str'),
429+
attr_type = self._ctx.api.named_type('builtins.dict', [
430+
self._ctx.api.named_type('builtins.str'),
431431
field_type,
432432
])
433433
var = Var(name=attr_name, type=attr_type)

mypy/plugins/functools.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,9 @@ def functools_total_ordering_maker_callback(ctx: mypy.plugin.ClassDefContext,
4545
return
4646

4747
other_type = _find_other_type(root_method)
48-
bool_type = ctx.api.named_type('__builtins__.bool')
48+
bool_type = ctx.api.named_type('builtins.bool')
4949
ret_type: Type = bool_type
50-
if root_method.type.ret_type != ctx.api.named_type('__builtins__.bool'):
50+
if root_method.type.ret_type != ctx.api.named_type('builtins.bool'):
5151
proper_ret_type = get_proper_type(root_method.type.ret_type)
5252
if not (isinstance(proper_ret_type, UnboundType)
5353
and proper_ret_type.name.split('.')[-1] == 'bool'):

mypy/semanal.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4411,13 +4411,13 @@ def builtin_type(self, fully_qualified_name: str) -> Instance:
44114411
return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars))
44124412

44134413
def object_type(self) -> Instance:
4414-
return self.named_type('__builtins__.object')
4414+
return self.named_type('builtins.object')
44154415

44164416
def str_type(self) -> Instance:
4417-
return self.named_type('__builtins__.str')
4417+
return self.named_type('builtins.str')
44184418

4419-
def named_type(self, qualified_name: str, args: Optional[List[Type]] = None) -> Instance:
4420-
sym = self.lookup_qualified(qualified_name, Context())
4419+
def named_type(self, fullname: str, args: Optional[List[Type]] = None) -> Instance:
4420+
sym = self.lookup_fully_qualified(fullname)
44214421
assert sym, "Internal error: attempted to construct unknown type"
44224422
node = sym.node
44234423
assert isinstance(node, TypeInfo)
@@ -4426,9 +4426,9 @@ def named_type(self, qualified_name: str, args: Optional[List[Type]] = None) ->
44264426
return Instance(node, args)
44274427
return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars))
44284428

4429-
def named_type_or_none(self, qualified_name: str,
4429+
def named_type_or_none(self, fullname: str,
44304430
args: Optional[List[Type]] = None) -> Optional[Instance]:
4431-
sym = self.lookup_fully_qualified_or_none(qualified_name)
4431+
sym = self.lookup_fully_qualified_or_none(fullname)
44324432
if not sym or isinstance(sym.node, PlaceholderNode):
44334433
return None
44344434
node = sym.node

mypy/semanal_infer.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def infer_decorator_signature_if_simple(dec: Decorator,
3030
[ARG_POS],
3131
[None],
3232
AnyType(TypeOfAny.special_form),
33-
analyzer.named_type('__builtins__.function'),
33+
analyzer.named_type('builtins.function'),
3434
name=dec.var.name)
3535
elif isinstance(dec.func.type, CallableType):
3636
dec.var.type = dec.func.type
@@ -47,7 +47,7 @@ def infer_decorator_signature_if_simple(dec: Decorator,
4747
if decorator_preserves_type:
4848
# No non-identity decorators left. We can trivially infer the type
4949
# of the function here.
50-
dec.var.type = function_type(dec.func, analyzer.named_type('__builtins__.function'))
50+
dec.var.type = function_type(dec.func, analyzer.named_type('builtins.function'))
5151
if dec.decorators:
5252
return_type = calculate_return_type(dec.decorators[0])
5353
if return_type and isinstance(return_type, AnyType):
@@ -58,7 +58,7 @@ def infer_decorator_signature_if_simple(dec: Decorator,
5858
if sig:
5959
# The outermost decorator always returns the same kind of function,
6060
# so we know that this is the type of the decorated function.
61-
orig_sig = function_type(dec.func, analyzer.named_type('__builtins__.function'))
61+
orig_sig = function_type(dec.func, analyzer.named_type('builtins.function'))
6262
sig.name = orig_sig.items[0].name
6363
dec.var.type = sig
6464

mypy/semanal_namedtuple.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -384,19 +384,19 @@ def build_namedtuple_typeinfo(self,
384384
types: List[Type],
385385
default_items: Mapping[str, Expression],
386386
line: int) -> TypeInfo:
387-
strtype = self.api.named_type('__builtins__.str')
387+
strtype = self.api.named_type('builtins.str')
388388
implicit_any = AnyType(TypeOfAny.special_form)
389-
basetuple_type = self.api.named_type('__builtins__.tuple', [implicit_any])
389+
basetuple_type = self.api.named_type('builtins.tuple', [implicit_any])
390390
dictype = (self.api.named_type_or_none('builtins.dict', [strtype, implicit_any])
391-
or self.api.named_type('__builtins__.object'))
391+
or self.api.named_type('builtins.object'))
392392
# Actual signature should return OrderedDict[str, Union[types]]
393393
ordereddictype = (self.api.named_type_or_none('builtins.dict', [strtype, implicit_any])
394-
or self.api.named_type('__builtins__.object'))
395-
fallback = self.api.named_type('__builtins__.tuple', [implicit_any])
394+
or self.api.named_type('builtins.object'))
395+
fallback = self.api.named_type('builtins.tuple', [implicit_any])
396396
# Note: actual signature should accept an invariant version of Iterable[UnionType[types]].
397397
# but it can't be expressed. 'new' and 'len' should be callable types.
398398
iterable_type = self.api.named_type_or_none('typing.Iterable', [implicit_any])
399-
function_type = self.api.named_type('__builtins__.function')
399+
function_type = self.api.named_type('builtins.function')
400400

401401
info = self.api.basic_new_typeinfo(name, fallback, line)
402402
info.is_named_tuple = True

mypy/semanal_newtype.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def process_newtype_declaration(self, s: AssignmentStmt) -> bool:
8484
self.fail(message.format(format_type(old_type)), s, code=codes.VALID_NEWTYPE)
8585
# Otherwise the error was already reported.
8686
old_type = AnyType(TypeOfAny.from_error)
87-
object_type = self.api.named_type('__builtins__.object')
87+
object_type = self.api.named_type('builtins.object')
8888
newtype_class_info = self.build_newtype_typeinfo(name, old_type, object_type, s.line)
8989
newtype_class_info.fallback_to_any = True
9090

@@ -194,7 +194,7 @@ def build_newtype_typeinfo(self, name: str, old_type: Type, base_type: Instance,
194194
arg_kinds=[arg.kind for arg in args],
195195
arg_names=['self', 'item'],
196196
ret_type=NoneType(),
197-
fallback=self.api.named_type('__builtins__.function'),
197+
fallback=self.api.named_type('builtins.function'),
198198
name=name)
199199
init_func = FuncDef('__init__', args, Block([]), typ=signature)
200200
init_func.info = info

mypy/semanal_shared.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,12 @@ def lookup(self, name: str, ctx: Context,
101101
raise NotImplementedError
102102

103103
@abstractmethod
104-
def named_type(self, qualified_name: str, args: Optional[List[Type]] = None) -> Instance:
104+
def named_type(self, fullname: str,
105+
args: Optional[List[Type]] = None) -> Instance:
105106
raise NotImplementedError
106107

107108
@abstractmethod
108-
def named_type_or_none(self, qualified_name: str,
109+
def named_type_or_none(self, fullname: str,
109110
args: Optional[List[Type]] = None) -> Optional[Instance]:
110111
raise NotImplementedError
111112

0 commit comments

Comments
 (0)