Skip to content

Commit

Permalink
Use lookup_fully_qualified for SemanticAnalyzer.named_type (python#11332
Browse files Browse the repository at this point in the history
)

Related to python#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.
  • Loading branch information
97littleleaf11 authored Oct 15, 2021
1 parent d807e09 commit 9bd6517
Show file tree
Hide file tree
Showing 10 changed files with 34 additions and 38 deletions.
6 changes: 3 additions & 3 deletions mypy/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,13 +250,13 @@ class SemanticAnalyzerPluginInterface:
msg: MessageBuilder

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

@abstractmethod
def named_type_or_none(self,
qualified_name: str,
def named_type_or_none(self, fullname: str,
args: Optional[List[Type]] = None) -> Optional[Instance]:
"""Construct an instance of a type with given type arguments.
Expand Down
6 changes: 3 additions & 3 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,8 +640,8 @@ def _parse_assignments(

def _add_order(ctx: 'mypy.plugin.ClassDefContext', adder: 'MethodAdder') -> None:
"""Generate all the ordering methods for this class."""
bool_type = ctx.api.named_type('__builtins__.bool')
object_type = ctx.api.named_type('__builtins__.object')
bool_type = ctx.api.named_type('builtins.bool')
object_type = ctx.api.named_type('builtins.object')
# Make the types be:
# AT = TypeVar('AT')
# def __lt__(self: AT, other: AT) -> bool
Expand Down Expand Up @@ -714,7 +714,7 @@ def _add_attrs_magic_attribute(ctx: 'mypy.plugin.ClassDefContext',
ctx.api.named_type_or_none('attr.Attribute', [attr_type or any_type]) or any_type
for attr_type in raw_attr_types
]
fallback_type = ctx.api.named_type('__builtins__.tuple', [
fallback_type = ctx.api.named_type('builtins.tuple', [
ctx.api.named_type_or_none('attr.Attribute', [any_type]) or any_type,
])
var = Var(name=attr_name, type=TupleType(attributes_types, fallback=fallback_type))
Expand Down
7 changes: 1 addition & 6 deletions mypy/plugins/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,8 @@ def add_method_to_class(
cls.defs.body.remove(sym.node)

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

Expand Down
10 changes: 5 additions & 5 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def transform(self) -> None:
if (decorator_arguments['eq'] and info.get('__eq__') is None or
decorator_arguments['order']):
# Type variable for self types in generated methods.
obj_type = ctx.api.named_type('__builtins__.object')
obj_type = ctx.api.named_type('builtins.object')
self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME,
[], obj_type)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
Expand All @@ -158,10 +158,10 @@ def transform(self) -> None:
for method_name in ['__lt__', '__gt__', '__le__', '__ge__']:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = ctx.api.named_type('__builtins__.object')
obj_type = ctx.api.named_type('builtins.object')
order_tvar_def = TypeVarType(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME,
-1, [], obj_type)
order_return_type = ctx.api.named_type('__builtins__.bool')
order_return_type = ctx.api.named_type('builtins.bool')
order_args = [
Argument(Var('other', order_tvar_def), order_tvar_def, None, ARG_POS)
]
Expand Down Expand Up @@ -426,8 +426,8 @@ def _add_dataclass_fields_magic_attribute(self) -> None:
attr_name = '__dataclass_fields__'
any_type = AnyType(TypeOfAny.explicit)
field_type = self._ctx.api.named_type_or_none('dataclasses.Field', [any_type]) or any_type
attr_type = self._ctx.api.named_type('__builtins__.dict', [
self._ctx.api.named_type('__builtins__.str'),
attr_type = self._ctx.api.named_type('builtins.dict', [
self._ctx.api.named_type('builtins.str'),
field_type,
])
var = Var(name=attr_name, type=attr_type)
Expand Down
4 changes: 2 additions & 2 deletions mypy/plugins/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ def functools_total_ordering_maker_callback(ctx: mypy.plugin.ClassDefContext,
return

other_type = _find_other_type(root_method)
bool_type = ctx.api.named_type('__builtins__.bool')
bool_type = ctx.api.named_type('builtins.bool')
ret_type: Type = bool_type
if root_method.type.ret_type != ctx.api.named_type('__builtins__.bool'):
if root_method.type.ret_type != ctx.api.named_type('builtins.bool'):
proper_ret_type = get_proper_type(root_method.type.ret_type)
if not (isinstance(proper_ret_type, UnboundType)
and proper_ret_type.name.split('.')[-1] == 'bool'):
Expand Down
12 changes: 6 additions & 6 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -4411,13 +4411,13 @@ def builtin_type(self, fully_qualified_name: str) -> Instance:
return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars))

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

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

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

def named_type_or_none(self, qualified_name: str,
def named_type_or_none(self, fullname: str,
args: Optional[List[Type]] = None) -> Optional[Instance]:
sym = self.lookup_fully_qualified_or_none(qualified_name)
sym = self.lookup_fully_qualified_or_none(fullname)
if not sym or isinstance(sym.node, PlaceholderNode):
return None
node = sym.node
Expand Down
6 changes: 3 additions & 3 deletions mypy/semanal_infer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def infer_decorator_signature_if_simple(dec: Decorator,
[ARG_POS],
[None],
AnyType(TypeOfAny.special_form),
analyzer.named_type('__builtins__.function'),
analyzer.named_type('builtins.function'),
name=dec.var.name)
elif isinstance(dec.func.type, CallableType):
dec.var.type = dec.func.type
Expand All @@ -47,7 +47,7 @@ def infer_decorator_signature_if_simple(dec: Decorator,
if decorator_preserves_type:
# No non-identity decorators left. We can trivially infer the type
# of the function here.
dec.var.type = function_type(dec.func, analyzer.named_type('__builtins__.function'))
dec.var.type = function_type(dec.func, analyzer.named_type('builtins.function'))
if dec.decorators:
return_type = calculate_return_type(dec.decorators[0])
if return_type and isinstance(return_type, AnyType):
Expand All @@ -58,7 +58,7 @@ def infer_decorator_signature_if_simple(dec: Decorator,
if sig:
# The outermost decorator always returns the same kind of function,
# so we know that this is the type of the decorated function.
orig_sig = function_type(dec.func, analyzer.named_type('__builtins__.function'))
orig_sig = function_type(dec.func, analyzer.named_type('builtins.function'))
sig.name = orig_sig.items[0].name
dec.var.type = sig

Expand Down
12 changes: 6 additions & 6 deletions mypy/semanal_namedtuple.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,19 +384,19 @@ def build_namedtuple_typeinfo(self,
types: List[Type],
default_items: Mapping[str, Expression],
line: int) -> TypeInfo:
strtype = self.api.named_type('__builtins__.str')
strtype = self.api.named_type('builtins.str')
implicit_any = AnyType(TypeOfAny.special_form)
basetuple_type = self.api.named_type('__builtins__.tuple', [implicit_any])
basetuple_type = self.api.named_type('builtins.tuple', [implicit_any])
dictype = (self.api.named_type_or_none('builtins.dict', [strtype, implicit_any])
or self.api.named_type('__builtins__.object'))
or self.api.named_type('builtins.object'))
# Actual signature should return OrderedDict[str, Union[types]]
ordereddictype = (self.api.named_type_or_none('builtins.dict', [strtype, implicit_any])
or self.api.named_type('__builtins__.object'))
fallback = self.api.named_type('__builtins__.tuple', [implicit_any])
or self.api.named_type('builtins.object'))
fallback = self.api.named_type('builtins.tuple', [implicit_any])
# Note: actual signature should accept an invariant version of Iterable[UnionType[types]].
# but it can't be expressed. 'new' and 'len' should be callable types.
iterable_type = self.api.named_type_or_none('typing.Iterable', [implicit_any])
function_type = self.api.named_type('__builtins__.function')
function_type = self.api.named_type('builtins.function')

info = self.api.basic_new_typeinfo(name, fallback, line)
info.is_named_tuple = True
Expand Down
4 changes: 2 additions & 2 deletions mypy/semanal_newtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def process_newtype_declaration(self, s: AssignmentStmt) -> bool:
self.fail(message.format(format_type(old_type)), s, code=codes.VALID_NEWTYPE)
# Otherwise the error was already reported.
old_type = AnyType(TypeOfAny.from_error)
object_type = self.api.named_type('__builtins__.object')
object_type = self.api.named_type('builtins.object')
newtype_class_info = self.build_newtype_typeinfo(name, old_type, object_type, s.line)
newtype_class_info.fallback_to_any = True

Expand Down Expand Up @@ -194,7 +194,7 @@ def build_newtype_typeinfo(self, name: str, old_type: Type, base_type: Instance,
arg_kinds=[arg.kind for arg in args],
arg_names=['self', 'item'],
ret_type=NoneType(),
fallback=self.api.named_type('__builtins__.function'),
fallback=self.api.named_type('builtins.function'),
name=name)
init_func = FuncDef('__init__', args, Block([]), typ=signature)
init_func.info = info
Expand Down
5 changes: 3 additions & 2 deletions mypy/semanal_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,12 @@ def lookup(self, name: str, ctx: Context,
raise NotImplementedError

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

@abstractmethod
def named_type_or_none(self, qualified_name: str,
def named_type_or_none(self, fullname: str,
args: Optional[List[Type]] = None) -> Optional[Instance]:
raise NotImplementedError

Expand Down

0 comments on commit 9bd6517

Please sign in to comment.