Skip to content

Commit b18281c

Browse files
Simplify boolean return logic in various places (#14012)
Co-authored-by: Shantanu <[email protected]>
1 parent 5cc1439 commit b18281c

File tree

11 files changed

+86
-118
lines changed

11 files changed

+86
-118
lines changed

misc/fix_annotate.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -213,8 +213,7 @@ def has_return_exprs(self, node):
213213
results = {}
214214
if self.return_expr.match(node, results):
215215
return True
216-
for child in node.children:
217-
if child.type not in (syms.funcdef, syms.classdef):
218-
if self.has_return_exprs(child):
219-
return True
220-
return False
216+
return any(
217+
child.type not in (syms.funcdef, syms.classdef) and self.has_return_exprs(child)
218+
for child in node.children
219+
)

mypy/build.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2728,11 +2728,8 @@ def in_partial_package(id: str, manager: BuildManager) -> bool:
27282728
else:
27292729
parent_mod = parent_st.tree
27302730
if parent_mod is not None:
2731-
if parent_mod.is_partial_stub_package:
2732-
return True
2733-
else:
2734-
# Bail out soon, complete subpackage found
2735-
return False
2731+
# Bail out soon, complete subpackage found
2732+
return parent_mod.is_partial_stub_package
27362733
id = parent
27372734
return False
27382735

@@ -3580,9 +3577,10 @@ def record_missing_stub_packages(cache_dir: str, missing_stub_packages: set[str]
35803577

35813578

35823579
def is_silent_import_module(manager: BuildManager, path: str) -> bool:
3583-
if not manager.options.no_silence_site_packages:
3584-
for dir in manager.search_paths.package_path + manager.search_paths.typeshed_path:
3585-
if is_sub_path(path, dir):
3586-
# Silence errors in site-package dirs and typeshed
3587-
return True
3588-
return False
3580+
if manager.options.no_silence_site_packages:
3581+
return False
3582+
# Silence errors in site-package dirs and typeshed
3583+
return any(
3584+
is_sub_path(path, dir)
3585+
for dir in manager.search_paths.package_path + manager.search_paths.typeshed_path
3586+
)

mypy/checker.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2292,9 +2292,7 @@ def is_final_enum_value(self, sym: SymbolTableNode) -> bool:
22922292
):
22932293
return False
22942294

2295-
if self.is_stub or sym.node.has_explicit_value:
2296-
return True
2297-
return False
2295+
return self.is_stub or sym.node.has_explicit_value
22982296

22992297
def check_enum_bases(self, defn: ClassDef) -> None:
23002298
"""
@@ -5978,10 +5976,7 @@ def store_type(self, node: Expression, typ: Type) -> None:
59785976
self._type_maps[-1][node] = typ
59795977

59805978
def has_type(self, node: Expression) -> bool:
5981-
for m in reversed(self._type_maps):
5982-
if node in m:
5983-
return True
5984-
return False
5979+
return any(node in m for m in reversed(self._type_maps))
59855980

59865981
def lookup_type_or_none(self, node: Expression) -> Type | None:
59875982
for m in reversed(self._type_maps):
@@ -6152,13 +6147,11 @@ def handle_partial_var_type(
61526147
return fixup_partial_type(typ)
61536148

61546149
def is_defined_in_base_class(self, var: Var) -> bool:
6155-
if var.info:
6156-
for base in var.info.mro[1:]:
6157-
if base.get(var.name) is not None:
6158-
return True
6159-
if var.info.fallback_to_any:
6160-
return True
6161-
return False
6150+
if not var.info:
6151+
return False
6152+
return var.info.fallback_to_any or any(
6153+
base.get(var.name) is not None for base in var.info.mro[1:]
6154+
)
61626155

61636156
def find_partial_types(self, var: Var) -> dict[Var, Context] | None:
61646157
"""Look for an active partial type scope containing variable.
@@ -6354,8 +6347,7 @@ def is_writable_attribute(self, node: Node) -> bool:
63546347
elif isinstance(node, OverloadedFuncDef) and node.is_property:
63556348
first_item = cast(Decorator, node.items[0])
63566349
return first_item.var.is_settable_property
6357-
else:
6358-
return False
6350+
return False
63596351

63606352
def get_isinstance_type(self, expr: Expression) -> list[TypeRange] | None:
63616353
if isinstance(expr, OpExpr) and expr.op == "|":

mypy/modulefinder.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -148,14 +148,11 @@ def __init__(self, sources: list[BuildSource]) -> None:
148148
self.source_modules[source.module] = source.path or ""
149149

150150
def is_source(self, file: MypyFile) -> bool:
151-
if file.path and file.path in self.source_paths:
152-
return True
153-
elif file._fullname in self.source_modules:
154-
return True
155-
elif self.source_text_present:
156-
return True
157-
else:
158-
return False
151+
return (
152+
(file.path and file.path in self.source_paths)
153+
or file._fullname in self.source_modules
154+
or self.source_text_present
155+
)
159156

160157

161158
class FindModuleCache:
@@ -573,11 +570,11 @@ def _is_compatible_stub_package(self, stub_dir: str) -> bool:
573570
whether the stubs are compatible with Python 2 and 3.
574571
"""
575572
metadata_fnam = os.path.join(stub_dir, "METADATA.toml")
576-
if os.path.isfile(metadata_fnam):
577-
with open(metadata_fnam, "rb") as f:
578-
metadata = tomllib.load(f)
579-
return bool(metadata.get("python3", True))
580-
return True
573+
if not os.path.isfile(metadata_fnam):
574+
return True
575+
with open(metadata_fnam, "rb") as f:
576+
metadata = tomllib.load(f)
577+
return bool(metadata.get("python3", True))
581578

582579
def find_modules_recursive(self, module: str) -> list[BuildSource]:
583580
module_path = self.find_module(module)

mypy/stubgen.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,10 +1309,7 @@ def is_private_name(self, name: str, fullname: str | None = None) -> bool:
13091309

13101310
def is_private_member(self, fullname: str) -> bool:
13111311
parts = fullname.split(".")
1312-
for part in parts:
1313-
if self.is_private_name(part):
1314-
return True
1315-
return False
1312+
return any(self.is_private_name(part) for part in parts)
13161313

13171314
def get_str_type_of_node(
13181315
self, rvalue: Expression, can_infer_optional: bool = False, can_be_any: bool = True

mypy/subtypes.py

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -429,22 +429,18 @@ def visit_erased_type(self, left: ErasedType) -> bool:
429429
# This may be encountered during type inference. The result probably doesn't
430430
# matter much.
431431
# TODO: it actually does matter, figure out more principled logic about this.
432-
if self.subtype_context.keep_erased_types:
433-
return False
434-
return True
432+
return not self.subtype_context.keep_erased_types
435433

436434
def visit_deleted_type(self, left: DeletedType) -> bool:
437435
return True
438436

439437
def visit_instance(self, left: Instance) -> bool:
440438
if left.type.fallback_to_any and not self.proper_subtype:
441-
if isinstance(self.right, NoneType):
442-
# NOTE: `None` is a *non-subclassable* singleton, therefore no class
443-
# can by a subtype of it, even with an `Any` fallback.
444-
# This special case is needed to treat descriptors in classes with
445-
# dynamic base classes correctly, see #5456.
446-
return False
447-
return True
439+
# NOTE: `None` is a *non-subclassable* singleton, therefore no class
440+
# can by a subtype of it, even with an `Any` fallback.
441+
# This special case is needed to treat descriptors in classes with
442+
# dynamic base classes correctly, see #5456.
443+
return not isinstance(self.right, NoneType)
448444
right = self.right
449445
if isinstance(right, TupleType) and mypy.typeops.tuple_fallback(right).type.is_enum:
450446
return self._is_subtype(left, mypy.typeops.tuple_fallback(right))
@@ -513,11 +509,7 @@ def check_mixed(
513509
isinstance(unpacked_type, Instance)
514510
and unpacked_type.type.fullname == "builtins.tuple"
515511
):
516-
if not all(
517-
is_equivalent(l, unpacked_type.args[0]) for l in compare_to
518-
):
519-
return False
520-
return True
512+
return all(is_equivalent(l, unpacked_type.args[0]) for l in compare_to)
521513
if isinstance(unpacked_type, TypeVarTupleType):
522514
return False
523515
if isinstance(unpacked_type, AnyType):
@@ -741,9 +733,8 @@ def visit_tuple_type(self, left: TupleType) -> bool:
741733
elif isinstance(right, TupleType):
742734
if len(left.items) != len(right.items):
743735
return False
744-
for l, r in zip(left.items, right.items):
745-
if not self._is_subtype(l, r):
746-
return False
736+
if any(not self._is_subtype(l, r) for l, r in zip(left.items, right.items)):
737+
return False
747738
rfallback = mypy.typeops.tuple_fallback(right)
748739
if is_named_instance(rfallback, "builtins.tuple"):
749740
# No need to verify fallback. This is useful since the calculated fallback
@@ -752,9 +743,7 @@ def visit_tuple_type(self, left: TupleType) -> bool:
752743
# join(Union[int, C], Union[str, C]) == Union[int, str, C].
753744
return True
754745
lfallback = mypy.typeops.tuple_fallback(left)
755-
if not self._is_subtype(lfallback, rfallback):
756-
return False
757-
return True
746+
return self._is_subtype(lfallback, rfallback)
758747
else:
759748
return False
760749

@@ -1368,8 +1357,7 @@ def g(x: int) -> int: ...
13681357
unified = unify_generic_callable(left, right, ignore_return=ignore_return)
13691358
if unified is None:
13701359
return False
1371-
else:
1372-
left = unified
1360+
left = unified
13731361

13741362
# If we allow partial overlaps, we don't need to leave R generic:
13751363
# if we can find even just a single typevar assignment which

mypy/typeanal.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1729,9 +1729,7 @@ def __init__(
17291729
def _seems_like_callable(self, type: UnboundType) -> bool:
17301730
if not type.args:
17311731
return False
1732-
if isinstance(type.args[0], (EllipsisType, TypeList, ParamSpecType)):
1733-
return True
1734-
return False
1732+
return isinstance(type.args[0], (EllipsisType, TypeList, ParamSpecType))
17351733

17361734
def visit_unbound_type(self, t: UnboundType) -> TypeVarLikeList:
17371735
name = t.name

mypy/types.py

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -437,14 +437,12 @@ def __repr__(self) -> str:
437437
return self.raw_id.__repr__()
438438

439439
def __eq__(self, other: object) -> bool:
440-
if isinstance(other, TypeVarId):
441-
return (
442-
self.raw_id == other.raw_id
443-
and self.meta_level == other.meta_level
444-
and self.namespace == other.namespace
445-
)
446-
else:
447-
return False
440+
return (
441+
isinstance(other, TypeVarId)
442+
and self.raw_id == other.raw_id
443+
and self.meta_level == other.meta_level
444+
and self.namespace == other.namespace
445+
)
448446

449447
def __ne__(self, other: object) -> bool:
450448
return not (self == other)
@@ -910,9 +908,7 @@ def __hash__(self) -> int:
910908
return hash(tuple(self.items))
911909

912910
def __eq__(self, other: object) -> bool:
913-
if not isinstance(other, TypeList):
914-
return False
915-
return self.items == other.items
911+
return isinstance(other, TypeList) and self.items == other.items
916912

917913

918914
class UnpackType(ProperType):
@@ -2263,16 +2259,19 @@ def __hash__(self) -> int:
22632259
return hash((frozenset(self.items.items()), self.fallback, frozenset(self.required_keys)))
22642260

22652261
def __eq__(self, other: object) -> bool:
2266-
if isinstance(other, TypedDictType):
2267-
if frozenset(self.items.keys()) != frozenset(other.items.keys()):
2268-
return False
2269-
for (_, left_item_type, right_item_type) in self.zip(other):
2270-
if not left_item_type == right_item_type:
2271-
return False
2272-
return self.fallback == other.fallback and self.required_keys == other.required_keys
2273-
else:
2262+
if not isinstance(other, TypedDictType):
22742263
return NotImplemented
22752264

2265+
return (
2266+
frozenset(self.items.keys()) == frozenset(other.items.keys())
2267+
and all(
2268+
left_item_type == right_item_type
2269+
for (_, left_item_type, right_item_type) in self.zip(other)
2270+
)
2271+
and self.fallback == other.fallback
2272+
and self.required_keys == other.required_keys
2273+
)
2274+
22762275
def serialize(self) -> JsonDict:
22772276
return {
22782277
".class": "TypedDictType",
@@ -3352,11 +3351,11 @@ def is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue
33523351
"""Check if this type is a LiteralType with the given fallback type and value."""
33533352
if isinstance(typ, Instance) and typ.last_known_value:
33543353
typ = typ.last_known_value
3355-
if not isinstance(typ, LiteralType):
3356-
return False
3357-
if typ.fallback.type.fullname != fallback_fullname:
3358-
return False
3359-
return typ.value == value
3354+
return (
3355+
isinstance(typ, LiteralType)
3356+
and typ.fallback.type.fullname == fallback_fullname
3357+
and typ.value == value
3358+
)
33603359

33613360

33623361
def is_self_type_like(typ: Type, *, is_classmethod: bool) -> bool:

mypyc/ir/class_ir.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -265,10 +265,7 @@ def has_attr(self, name: str) -> bool:
265265
return True
266266

267267
def is_deletable(self, name: str) -> bool:
268-
for ir in self.mro:
269-
if name in ir.deletable:
270-
return True
271-
return False
268+
return any(name in ir.deletable for ir in self.mro)
272269

273270
def is_always_defined(self, name: str) -> bool:
274271
if self.is_deletable(name):

mypyc/irbuild/prebuildvisitor.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -162,12 +162,10 @@ def visit_symbol_node(self, symbol: SymbolNode) -> None:
162162
def is_parent(self, fitem: FuncItem, child: FuncItem) -> bool:
163163
# Check if child is nested within fdef (possibly indirectly
164164
# within multiple nested functions).
165-
if child in self.nested_funcs:
166-
parent = self.nested_funcs[child]
167-
if parent == fitem:
168-
return True
169-
return self.is_parent(fitem, parent)
170-
return False
165+
if child not in self.nested_funcs:
166+
return False
167+
parent = self.nested_funcs[child]
168+
return parent == fitem or self.is_parent(fitem, parent)
171169

172170
def add_free_variable(self, symbol: SymbolNode) -> None:
173171
# Find the function where the symbol was (likely) first declared,

mypyc/irbuild/prepare.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -178,15 +178,20 @@ def prepare_method_def(
178178

179179
def is_valid_multipart_property_def(prop: OverloadedFuncDef) -> bool:
180180
# Checks to ensure supported property decorator semantics
181-
if len(prop.items) == 2:
182-
getter = prop.items[0]
183-
setter = prop.items[1]
184-
if isinstance(getter, Decorator) and isinstance(setter, Decorator):
185-
if getter.func.is_property and len(setter.decorators) == 1:
186-
if isinstance(setter.decorators[0], MemberExpr):
187-
if setter.decorators[0].name == "setter":
188-
return True
189-
return False
181+
if len(prop.items) != 2:
182+
return False
183+
184+
getter = prop.items[0]
185+
setter = prop.items[1]
186+
187+
return (
188+
isinstance(getter, Decorator)
189+
and isinstance(setter, Decorator)
190+
and getter.func.is_property
191+
and len(setter.decorators) == 1
192+
and isinstance(setter.decorators[0], MemberExpr)
193+
and setter.decorators[0].name == "setter"
194+
)
190195

191196

192197
def can_subclass_builtin(builtin_base: str) -> bool:

0 commit comments

Comments
 (0)