Skip to content

Commit a4e49a4

Browse files
AlexWaygoodwarsaw
authored andcommitted
pythongh-103193: Use LBYL idioms rather than EAFP in inspect.getattr_static (python#103318)
1 parent e23bf26 commit a4e49a4

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

Lib/inspect.py

+10-15
Original file line numberDiff line numberDiff line change
@@ -1787,11 +1787,8 @@ def _check_instance(obj, attr):
17871787

17881788
def _check_class(klass, attr):
17891789
for entry in _static_getmro(klass):
1790-
if _shadowed_dict(type(entry)) is _sentinel:
1791-
try:
1792-
return entry.__dict__[attr]
1793-
except KeyError:
1794-
pass
1790+
if _shadowed_dict(type(entry)) is _sentinel and attr in entry.__dict__:
1791+
return entry.__dict__[attr]
17951792
return _sentinel
17961793

17971794
def _is_type(obj):
@@ -1803,11 +1800,9 @@ def _is_type(obj):
18031800

18041801
def _shadowed_dict(klass):
18051802
for entry in _static_getmro(klass):
1806-
try:
1807-
class_dict = _get_dunder_dict_of_class(entry)["__dict__"]
1808-
except KeyError:
1809-
pass
1810-
else:
1803+
dunder_dict = _get_dunder_dict_of_class(entry)
1804+
if '__dict__' in dunder_dict:
1805+
class_dict = dunder_dict['__dict__']
18111806
if not (type(class_dict) is types.GetSetDescriptorType and
18121807
class_dict.__name__ == "__dict__" and
18131808
class_dict.__objclass__ is entry):
@@ -1850,11 +1845,11 @@ def getattr_static(obj, attr, default=_sentinel):
18501845
if obj is klass:
18511846
# for types we check the metaclass too
18521847
for entry in _static_getmro(type(klass)):
1853-
if _shadowed_dict(type(entry)) is _sentinel:
1854-
try:
1855-
return entry.__dict__[attr]
1856-
except KeyError:
1857-
pass
1848+
if (
1849+
_shadowed_dict(type(entry)) is _sentinel
1850+
and attr in entry.__dict__
1851+
):
1852+
return entry.__dict__[attr]
18581853
if default is not _sentinel:
18591854
return default
18601855
raise AttributeError(attr)

0 commit comments

Comments
 (0)