Skip to content

Commit 652ec81

Browse files
msullivanroot
authored andcommitted
Micro-optimization of TypeInfo.__bool__ (python#5712)
In conjunction with a change that makes mypyc able to directly generate calls to `__bool__`, this allows us to generate a much more direct check for truthiness of TypeInfo.
1 parent ad935cb commit 652ec81

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

mypy/nodes.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2296,6 +2296,12 @@ def __getitem__(self, name: str) -> 'SymbolTableNode':
22962296
def __repr__(self) -> str:
22972297
return '<TypeInfo %s>' % self.fullname()
22982298

2299+
def __bool__(self) -> bool:
2300+
# We defined this here instead of just overriding it in
2301+
# FakeInfo so that mypyc can generate a direct call instead of
2302+
# using the generic bool handling.
2303+
return not isinstance(self, FakeInfo)
2304+
22992305
def has_readable_member(self, name: str) -> bool:
23002306
return self.get(name) is not None
23012307

@@ -2472,15 +2478,12 @@ class FakeInfo(TypeInfo):
24722478
# for missing TypeInfos in a number of places where the excuses
24732479
# for not being Optional are a little weaker.
24742480
#
2475-
# It defines a __bool__ method so that it can be conveniently
2476-
# tested against in the same way that it would be if things were
2477-
# properly optional.
2481+
# TypeInfo defines a __bool__ method that returns False for FakeInfo
2482+
# so that it can be conveniently tested against in the same way that it
2483+
# would be if things were properly optional.
24782484
def __init__(self, msg: str) -> None:
24792485
self.msg = msg
24802486

2481-
def __bool__(self) -> bool:
2482-
return False
2483-
24842487
def __getattribute__(self, attr: str) -> None:
24852488
raise AssertionError(object.__getattribute__(self, 'msg'))
24862489

0 commit comments

Comments
 (0)