Skip to content

Commit 6e9a69d

Browse files
committed
Adds a brain to mock the __class_getitem__ method on the type class (only with python3.9)
1 parent c9fd193 commit 6e9a69d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

astroid/brain/brain_type.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# -*- coding: utf-8 -*-
2+
import sys
3+
4+
from astroid import (
5+
MANAGER,
6+
UseInferenceDefault,
7+
extract_node,
8+
inference_tip,
9+
nodes,
10+
InferenceError,
11+
Name,
12+
)
13+
14+
15+
def _looks_like_type_subscript(node):
16+
"""Try to figure out if a Subscript node *might* be a typing-related subscript"""
17+
if isinstance(node, nodes.Name):
18+
return node.name == "type"
19+
if isinstance(node, nodes.Subscript):
20+
if isinstance(node.value, Name) and node.value.name == "type":
21+
return True
22+
return False
23+
24+
25+
def infer_type_sub(node, context=None):
26+
"""Infer a typing.X[...] subscript"""
27+
sub_node = node.parent
28+
if not isinstance(sub_node, nodes.Subscript):
29+
raise UseInferenceDefault
30+
class_src = """
31+
class type:
32+
def __class_getitem__(cls, key):
33+
return cls
34+
"""
35+
node = extract_node(class_src)
36+
return node.infer(context=context)
37+
38+
39+
40+
if sys.version_info[:2] == (3, 9):
41+
MANAGER.register_transform(
42+
nodes.Name, inference_tip(infer_type_sub), _looks_like_type_subscript
43+
)

0 commit comments

Comments
 (0)