Skip to content

Commit a1f85dd

Browse files
committed
lispy-python.py: Add some type annotations
1 parent f6a65ae commit a1f85dd

File tree

2 files changed

+33
-38
lines changed

2 files changed

+33
-38
lines changed

Cookbook.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@ def test(recipe):
22
return ["pytest test/test_lispy-python.py"]
33

44
def typecheck(recipe):
5-
return "dmypy run lispy-python.py"
5+
return "dmypy run -- lispy-python.py"
66

7-
del typecheck
7+
# del typecheck

lispy-python.py

+31-36
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@
2929
import shlex
3030
import subprocess
3131
import sys
32-
import types
3332
from ast import AST
3433
from contextlib import redirect_stdout
35-
from typing import List, Dict, Any, Union, Tuple, Optional, TypedDict
34+
from typing import List, Dict, Any, Union, Tuple, Optional, TypedDict, Callable
35+
from types import TracebackType, MethodType, FunctionType
3636

37-
def sh(cmd):
37+
def sh(cmd: str) -> str:
3838
r = subprocess.run(
3939
shlex.split(cmd),
4040
stdout=subprocess.PIPE,
@@ -63,7 +63,7 @@ def sh(cmd):
6363
class Stack:
6464
line_numbers: Dict[Tuple[str, str], int] = {}
6565

66-
def __init__(self, tb):
66+
def __init__(self, tb: Optional[TracebackType]):
6767
self.stack = []
6868
self.stack_idx = 0
6969
while tb:
@@ -79,13 +79,13 @@ def __init__(self, tb):
7979
if self.stack_top >= 0:
8080
self.set_frame(self.stack_top)
8181

82-
def frame_string(self, i):
82+
def frame_string(self, i: int) -> str:
8383
(fname, line, f) = self.stack[i]
8484
res = " File \"%s\", line %d, Frame [%d/%d] (%s):" % (
8585
f.f_code.co_filename, line, i, self.stack_top, f.f_code.co_name)
8686
return res
8787

88-
def __repr__(self):
88+
def __repr__(self) -> str:
8989
frames = []
9090
for i in range(self.stack_top + 1):
9191
s = self.frame_string(i)
@@ -94,7 +94,7 @@ def __repr__(self):
9494
frames.append(s)
9595
return "\n".join(frames)
9696

97-
def set_frame(self, i):
97+
def set_frame(self, i: int) -> None:
9898
if i >= 0:
9999
f = self.stack[i][2]
100100
self.stack_idx = i
@@ -107,15 +107,15 @@ def set_frame(self, i):
107107

108108
print(self.frame_string(self.stack_idx))
109109

110-
def up(self, delta=1):
110+
def up(self, delta: int = 1) -> None:
111111
if self.stack_idx <= 0:
112112
if self.stack:
113113
print(self.frame_string(self.stack_idx))
114114
else:
115115
self.stack_idx = max(self.stack_idx - delta, 0)
116116
self.set_frame(self.stack_idx)
117117

118-
def down(self, delta=1):
118+
def down(self, delta: int = 1) -> None:
119119
if self.stack_idx >= self.stack_top:
120120
if self.stack:
121121
print(self.frame_string(self.stack_idx))
@@ -124,21 +124,21 @@ def down(self, delta=1):
124124
self.set_frame(self.stack_idx)
125125

126126
class Autocall:
127-
def __init__(self, f):
127+
def __init__(self, f: Callable):
128128
self.f = f
129129

130-
def __call__(self, n):
130+
def __call__(self, n: Any) -> None:
131131
self.f(n)
132132

133-
def __repr__(self):
133+
def __repr__(self) -> str:
134134
try:
135135
self.f()
136136
except:
137137
pass
138138
return ""
139139

140140
#* Functions
141-
def chfile(f):
141+
def chfile(f: str) -> None:
142142
tf = top_level()
143143
tf.f_globals["__file__"] = f
144144
d = os.path.dirname(f)
@@ -147,36 +147,31 @@ def chfile(f):
147147
except:
148148
pass
149149

150-
def format_arg(arg_pair):
151-
name, default_value = arg_pair
152-
if default_value:
153-
return name + " = " + default_value
154-
else:
155-
return name
156-
157-
def arglist(sym):
150+
def arglist(sym: Callable) -> List[str]:
151+
def format_arg(arg_pair: Tuple[str, Optional[str]]) -> str:
152+
name, default_value = arg_pair
153+
if default_value:
154+
return name + " = " + default_value
155+
else:
156+
return name
158157
arg_info = inspect.getfullargspec(sym)
159158
if "self" in arg_info.args:
160159
arg_info.args.remove("self")
161160
if arg_info.defaults:
162-
defaults = (
163-
[None] * (len(arg_info.args) - len(arg_info.defaults)) +
164-
[repr(x) for x in arg_info.defaults])
161+
defaults: List[Optional[str]] = [None] * (len(arg_info.args) - len(arg_info.defaults))
162+
defaults += [repr(x) for x in arg_info.defaults]
165163
args = [format_arg(x) for x in zip(arg_info.args, defaults)]
166164
else:
167165
args = arg_info.args
168166
if arg_info.varargs:
169167
args += arg_info.varargs
170168
keywords = arg_info.kwonlydefaults
171169
if keywords:
172-
if type(keywords) is dict:
173-
for k, v in keywords.items():
174-
args.append(f"{k} = {v}")
175-
else:
176-
args.append("**" + keywords)
170+
for k, v in keywords.items():
171+
args.append(f"{k} = {v}")
177172
return args
178173

179-
def print_elisp(obj, end="\n"):
174+
def print_elisp(obj: Any, end: str = "\n") -> None:
180175
if hasattr(obj, "_asdict") and obj._asdict is not None:
181176
# namedtuple
182177
try:
@@ -302,7 +297,7 @@ def list_step(varname, lst):
302297
f_globals[varname] = val
303298
return val
304299

305-
def argv(cmd):
300+
def argv(cmd: str) -> None:
306301
sys.argv = shlex.split(cmd)
307302

308303
def find_global_vars(class_name):
@@ -320,11 +315,11 @@ def rebind(method, fname=None, line=None):
320315
(cls_name, fun_name) = qname.split(".")
321316
for (n, v) in find_global_vars(cls_name):
322317
print("rebind:", n)
323-
top_level().f_globals[n].__dict__[fun_name] = types.MethodType(top_level().f_globals[fun_name], v)
318+
top_level().f_globals[n].__dict__[fun_name] = MethodType(top_level().f_globals[fun_name], v)
324319
if fname and line:
325320
Stack.line_numbers[(fname, qname)] = line
326321

327-
def pm():
322+
def pm() -> None:
328323
"""Post mortem: recover the locals and globals from the last traceback."""
329324
if hasattr(sys, 'last_traceback'):
330325
stack = Stack(sys.last_traceback)
@@ -335,7 +330,7 @@ def pm():
335330
tl.f_globals["dn"] = Autocall(stack.down)
336331
globals()["stack"] = stack
337332

338-
def pprint(x):
333+
def pprint(x: Any) -> None:
339334
r1 = repr(x)
340335
if len(r1) > 1000 and repr1:
341336
print(repr1.repr(x))
@@ -345,7 +340,7 @@ def pprint(x):
345340
else:
346341
pp.PrettyPrinter(width=200).pprint(x)
347342

348-
def to_str(x):
343+
def to_str(x: Any) -> str:
349344
with io.StringIO() as buf, redirect_stdout(buf):
350345
pprint(x)
351346
return buf.getvalue().strip()
@@ -357,7 +352,7 @@ def step_in(fn, *args):
357352
f_globals[arg_name] = arg_val
358353

359354
def step_into_module_maybe(module):
360-
if isinstance(module, types.FunctionType):
355+
if isinstance(module, FunctionType):
361356
try:
362357
module = sys.modules[module.__module__]
363358
except:

0 commit comments

Comments
 (0)