|
1 | 1 | # -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Astroid hooks for type support. |
| 4 | +
|
| 5 | +Starting from python3.9, type object behaves as it had __class_getitem__ method. |
| 6 | +However it was not possible to simply add this method inside type's body, otherwise |
| 7 | +all types would also have this method. In this case it would have been possible |
| 8 | +to write str[int]. |
| 9 | +Guido Van Rossum proposed a hack to handle this in the interpreter: |
| 10 | +https://github.com/python/cpython/blob/master/Objects/abstract.c#L186-L189 |
| 11 | +
|
| 12 | +This brain follows the same logic. It is no wise to add permanently the __class_getitem__ method |
| 13 | +to the type object. Instead we choose to add it only in the case of a subscript node |
| 14 | +which inside name node is type. |
| 15 | +Doing this type[int] is allowed whereas str[int] is not. |
| 16 | +
|
| 17 | +Thanks to Lukasz Langa for fruitful discussion. |
| 18 | +""" |
2 | 19 | import sys |
3 | 20 |
|
4 | 21 | from astroid import ( |
|
10 | 27 |
|
11 | 28 |
|
12 | 29 | def _looks_like_type_subscript(node): |
13 | | - """Try to figure out if a Subscript node *might* be a typing-related subscript""" |
14 | | - if isinstance(node, nodes.Name): |
| 30 | + """ |
| 31 | + Try to figure out if a Name node is used inside a type related subscript |
| 32 | +
|
| 33 | + :param node: node to check |
| 34 | + :type node: nodes.Name |
| 35 | + :return: true if the node is a Name node inside a type related subscript |
| 36 | + :rtype: bool |
| 37 | + """ |
| 38 | + if isinstance(node, nodes.Name) and isinstance(node.parent, nodes.Subscript): |
15 | 39 | return node.name == "type" |
16 | | - if isinstance(node, nodes.Subscript): |
17 | | - if isinstance(node.value, Name) and node.value.name == "type": |
18 | | - return True |
19 | 40 | return False |
20 | 41 |
|
21 | 42 |
|
22 | 43 | def infer_type_sub(node, context=None): |
23 | | - """Infer a typing.X[...] subscript""" |
24 | | - sub_node = node.parent |
25 | | - if not isinstance(sub_node, nodes.Subscript): |
26 | | - raise UseInferenceDefault |
| 44 | + """ |
| 45 | + Infer a type[...] subscript |
| 46 | +
|
| 47 | + :param node: node to infer |
| 48 | + :type node: astroid.node_classes.NodeNG |
| 49 | + :param context: inference context |
| 50 | + :type context: astroid.context.InferenceContext |
| 51 | + :return: the inferred node |
| 52 | + :rtype: nodes.NodeNG |
| 53 | + """ |
27 | 54 | class_src = """ |
28 | 55 | class type: |
29 | 56 | def __class_getitem__(cls, key): |
|
0 commit comments