Skip to content

Commit 440dcde

Browse files
wheerdilevkivskyi
authored andcommitted
Make get_type_hints not throw an error on builtin methods (#368)
* Added support to get_type_hints for builtin methods like object.__init__ or object.__str__ etc. * Fixed tabs vs spaces -.- * Changed the type check for builtin functions/methods to use the new types in the types module.
1 parent 1229efb commit 440dcde

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/test_typing.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1542,12 +1542,15 @@ def meth(x: int): ...
15421542
class Der(ABase): ...
15431543
self.assertEqual(gth(ABase.meth), {'x': int})
15441544

1545-
def test_get_type_hints_for_builins(self):
1545+
def test_get_type_hints_for_builtins(self):
15461546
# Should not fail for built-in classes and functions.
15471547
self.assertEqual(gth(int), {})
15481548
self.assertEqual(gth(type), {})
15491549
self.assertEqual(gth(dir), {})
15501550
self.assertEqual(gth(len), {})
1551+
self.assertEqual(gth(object.__str__), {})
1552+
self.assertEqual(gth(object().__str__), {})
1553+
self.assertEqual(gth(str.join), {})
15511554

15521555
def test_previous_behavior(self):
15531556
def testf(x, y): ...

src/typing.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@
1010
import collections.abc as collections_abc
1111
except ImportError:
1212
import collections as collections_abc # Fallback for PY3.2.
13+
try:
14+
from types import SlotWrapperType, MethodWrapperType, MethodDescriptorType
15+
except ImportError:
16+
SlotWrapperType = type(object.__init__)
17+
MethodWrapperType = type(object().__str__)
18+
MethodDescriptorType = type(str.join)
1319

1420

1521
# Please keep __all__ alphabetized within each category.
@@ -1459,7 +1465,10 @@ def get_type_hints(obj, globalns=None, localns=None):
14591465
isinstance(obj, types.FunctionType) or
14601466
isinstance(obj, types.BuiltinFunctionType) or
14611467
isinstance(obj, types.MethodType) or
1462-
isinstance(obj, types.ModuleType)
1468+
isinstance(obj, types.ModuleType) or
1469+
isinstance(obj, SlotWrapperType) or
1470+
isinstance(obj, MethodWrapperType) or
1471+
isinstance(obj, MethodDescriptorType)
14631472
):
14641473
return {}
14651474
else:

0 commit comments

Comments
 (0)