-
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathast_compat.py
More file actions
80 lines (61 loc) · 2.2 KB
/
ast_compat.py
File metadata and controls
80 lines (61 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
The is a backwards compatible shim for the ast module.
This is the best way to make the ast module work the same in both python 2 and 3.
This is essentially what the ast module was doing until 3.12, when it started throwing
deprecation warnings.
"""
from ast import *
# Ideally we don't import anything else
if 'TypeAlias' in globals():
# Add n and s properties to Constant so it can stand in for Num, Str and Bytes
Constant.n = property(lambda self: self.value, lambda self, value: setattr(self, 'value', value)) # type: ignore[assignment]
Constant.s = property(lambda self: self.value, lambda self, value: setattr(self, 'value', value)) # type: ignore[assignment]
# These classes are redefined from the ones in ast that complain about deprecation
# They will continue to work once they are removed from ast
class Str(Constant): # type: ignore[no-redef]
def __new__(cls, s, *args, **kwargs):
return Constant(value=s, *args, **kwargs)
class Bytes(Constant): # type: ignore[no-redef]
def __new__(cls, s, *args, **kwargs):
return Constant(value=s, *args, **kwargs)
class Num(Constant): # type: ignore[no-redef]
def __new__(cls, n, *args, **kwargs):
return Constant(value=n, *args, **kwargs)
class NameConstant(Constant): # type: ignore[no-redef]
def __new__(cls, *args, **kwargs):
return Constant(*args, **kwargs)
class Ellipsis(Constant): # type: ignore[no-redef]
def __new__(cls, *args, **kwargs):
return Constant(value=literal_eval('...'), *args, **kwargs)
# Create a dummy class for missing AST nodes
for _node_type in [
'AnnAssign',
'AsyncFor',
'AsyncFunctionDef',
'AsyncFunctionDef',
'AsyncWith',
'Bytes',
'Constant',
'DictComp',
'Exec',
'ListComp',
'MatchAs',
'MatchMapping',
'MatchStar',
'NameConstant',
'NamedExpr',
'Nonlocal',
'ParamSpec',
'SetComp',
'Starred',
'TryStar',
'TypeVar',
'TypeVarTuple',
'TemplateStr',
'Interpolation',
'YieldFrom',
'arg',
'withitem',
]:
if _node_type not in globals():
globals()[_node_type] = type(_node_type, (AST,), {})