Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9cd8a95

Browse files
authored
some more typing (#14220)
2 parents 1229389 + 87ab1c5 commit 9cd8a95

8 files changed

Lines changed: 74 additions & 42 deletions

File tree

IPython/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
# encoding: utf-8
33
"""Terminal-based IPython entry point.
44
"""
5-
#-----------------------------------------------------------------------------
5+
# -----------------------------------------------------------------------------
66
# Copyright (c) 2012, IPython Development Team.
77
#
88
# Distributed under the terms of the Modified BSD License.
99
#
1010
# The full license is in the file COPYING.txt, distributed with this software.
11-
#-----------------------------------------------------------------------------
11+
# -----------------------------------------------------------------------------
1212

1313
from IPython import start_ipython
1414

IPython/core/completerlib.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,8 @@ def try_import(mod: str, only_modules=False) -> List[str]:
190190
completions.extend(m_all)
191191

192192
if m_is_init:
193-
completions.extend(module_list(os.path.dirname(m.__file__)))
193+
file_ = m.__file__
194+
completions.extend(module_list(os.path.dirname(file_)))
194195
completions_set = {c for c in completions if isinstance(c, str)}
195196
completions_set.discard('__init__')
196197
return list(completions_set)

IPython/core/inputsplitter.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@
3131
import tokenize
3232
import warnings
3333

34-
from typing import List, Tuple, Union
34+
from typing import List, Tuple, Union, Optional
35+
from types import CodeType
3536

3637
from IPython.core.inputtransformer import (leading_indent,
3738
classic_prompt,
@@ -336,7 +337,7 @@ class InputSplitter(object):
336337
# Code object corresponding to the current source. It is automatically
337338
# synced to the source, so it can be queried at any time to obtain the code
338339
# object; it will be None if the source doesn't compile to valid Python.
339-
code = None
340+
code: Optional[CodeType] = None
340341

341342
# Private attributes
342343

@@ -345,9 +346,9 @@ class InputSplitter(object):
345346
# Command compiler
346347
_compile: codeop.CommandCompiler
347348
# Boolean indicating whether the current block is complete
348-
_is_complete = None
349+
_is_complete: Optional[bool] = None
349350
# Boolean indicating whether the current block has an unrecoverable syntax error
350-
_is_invalid = False
351+
_is_invalid: bool = False
351352

352353
def __init__(self) -> None:
353354
"""Create a new InputSplitter instance."""

IPython/core/inputtransformer.py

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,8 @@ def wrap(cls, func):
7171
"""
7272
@functools.wraps(func)
7373
def transformer_factory(**kwargs):
74-
return cls(func, **kwargs)
75-
74+
return cls(func, **kwargs) # type: ignore [call-arg]
75+
7676
return transformer_factory
7777

7878
class StatelessInputTransformer(InputTransformer):
@@ -194,7 +194,7 @@ def assemble_logical_lines():
194194
line = ''.join(parts)
195195

196196
# Utilities
197-
def _make_help_call(target, esc, lspace):
197+
def _make_help_call(target: str, esc: str, lspace: str) -> str:
198198
"""Prepares a pinfo(2)/psearch call from a target name and the escape
199199
(i.e. ? or ??)"""
200200
method = 'pinfo2' if esc == '??' \
@@ -212,25 +212,28 @@ def _make_help_call(target, esc, lspace):
212212

213213

214214
# These define the transformations for the different escape characters.
215-
def _tr_system(line_info):
215+
def _tr_system(line_info: LineInfo):
216216
"Translate lines escaped with: !"
217217
cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
218218
return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
219219

220-
def _tr_system2(line_info):
220+
221+
def _tr_system2(line_info: LineInfo):
221222
"Translate lines escaped with: !!"
222223
cmd = line_info.line.lstrip()[2:]
223224
return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
224225

225-
def _tr_help(line_info):
226+
227+
def _tr_help(line_info: LineInfo):
226228
"Translate lines escaped with: ?/??"
227229
# A naked help line should just fire the intro help screen
228230
if not line_info.line[1:]:
229231
return 'get_ipython().show_usage()'
230232

231233
return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
232234

233-
def _tr_magic(line_info):
235+
236+
def _tr_magic(line_info: LineInfo):
234237
"Translate lines escaped with: %"
235238
tpl = '%sget_ipython().run_line_magic(%r, %r)'
236239
if line_info.line.startswith(ESC_MAGIC2):
@@ -241,17 +244,20 @@ def _tr_magic(line_info):
241244
t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
242245
return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)
243246

244-
def _tr_quote(line_info):
247+
248+
def _tr_quote(line_info: LineInfo):
245249
"Translate lines escaped with: ,"
246250
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
247251
'", "'.join(line_info.the_rest.split()) )
248252

249-
def _tr_quote2(line_info):
253+
254+
def _tr_quote2(line_info: LineInfo):
250255
"Translate lines escaped with: ;"
251256
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
252257
line_info.the_rest)
253258

254-
def _tr_paren(line_info):
259+
260+
def _tr_paren(line_info: LineInfo):
255261
"Translate lines escaped with: /"
256262
return '%s%s(%s)' % (line_info.pre, line_info.ifun,
257263
", ".join(line_info.the_rest.split()))
@@ -266,9 +272,8 @@ def _tr_paren(line_info):
266272
ESC_PAREN : _tr_paren }
267273

268274
@StatelessInputTransformer.wrap
269-
def escaped_commands(line):
270-
"""Transform escaped commands - %magic, !system, ?help + various autocalls.
271-
"""
275+
def escaped_commands(line: str):
276+
"""Transform escaped commands - %magic, !system, ?help + various autocalls."""
272277
if not line or line.isspace():
273278
return line
274279
lineinf = LineInfo(line)
@@ -342,20 +347,22 @@ def ends_in_comment_or_string(src):
342347

343348

344349
@StatelessInputTransformer.wrap
345-
def help_end(line):
350+
def help_end(line: str):
346351
"""Translate lines with ?/?? at the end"""
347352
m = _help_end_re.search(line)
348353
if m is None or ends_in_comment_or_string(line):
349354
return line
350355
target = m.group(1)
351356
esc = m.group(3)
352-
lspace = _initial_space_re.match(line).group(0)
357+
match = _initial_space_re.match(line)
358+
assert match is not None
359+
lspace = match.group(0)
353360

354361
return _make_help_call(target, esc, lspace)
355362

356363

357364
@CoroutineInputTransformer.wrap
358-
def cellmagic(end_on_blank_line=False):
365+
def cellmagic(end_on_blank_line: bool = False):
359366
"""Captures & transforms cell magics.
360367
361368
After a cell magic is started, this stores up any lines it gets until it is

IPython/utils/py3compat.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ def execfile(fname, glob, loc=None, compiler=None):
5757

5858
PYPY = platform.python_implementation() == "PyPy"
5959

60+
6061
# Cython still rely on that as a Dec 28 2019
6162
# See https://github.com/cython/cython/pull/3291 and
6263
# https://github.com/ipython/ipython/issues/12068

IPython/utils/text.py

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
from string import Formatter
1818
from pathlib import Path
1919

20+
from typing import List, Union, Optional, Dict, Tuple
21+
2022

2123
class LSString(str):
2224
"""String derivative with a special access attributes.
@@ -627,7 +629,7 @@ def _col_chunks(l, max_rows, row_first=False):
627629
yield l[i:(i + max_rows)]
628630

629631

630-
def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
632+
def _find_optimal(rlist, row_first: bool, separator_size: int, displaywidth: int):
631633
"""Calculate optimal info to columnize a list of string"""
632634
for max_rows in range(1, len(rlist) + 1):
633635
col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
@@ -650,7 +652,9 @@ def _get_or_default(mylist, i, default=None):
650652
return mylist[i]
651653

652654

653-
def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
655+
def compute_item_matrix(
656+
items, row_first: bool = False, empty=None, *, separator_size=2, displaywidth=80
657+
) -> Tuple[List[List[int]], Dict[str, int]]:
654658
"""Returns a nested list, and info to columnize items
655659
656660
Parameters
@@ -705,8 +709,13 @@ def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
705709
stacklevel=2,
706710
category=PendingDeprecationWarning,
707711
)
708-
info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
709-
nrow, ncol = info['max_rows'], info['num_columns']
712+
info = _find_optimal(
713+
list(map(len, items)),
714+
row_first,
715+
separator_size=separator_size,
716+
displaywidth=displaywidth,
717+
)
718+
nrow, ncol = info["max_rows"], info["num_columns"]
710719
if row_first:
711720
return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
712721
else:
@@ -740,13 +749,21 @@ def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=Fa
740749
category=PendingDeprecationWarning,
741750
)
742751
if not items:
743-
return '\n'
744-
matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
752+
return "\n"
753+
matrix: List[List[int]]
754+
matrix, info = compute_item_matrix(
755+
items,
756+
row_first=row_first,
757+
separator_size=len(separator),
758+
displaywidth=displaywidth,
759+
)
745760
if spread:
746-
separator = separator.ljust(int(info['optimal_separator_width']))
747-
fmatrix = [filter(None, x) for x in matrix]
748-
sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
749-
return '\n'.join(map(sjoin, fmatrix))+'\n'
761+
separator = separator.ljust(int(info["optimal_separator_width"]))
762+
fmatrix: List[filter[int]] = [filter(None, x) for x in matrix]
763+
sjoin = lambda x: separator.join(
764+
[y.ljust(w, " ") for y, w in zip(x, info["column_widths"])]
765+
)
766+
return "\n".join(map(sjoin, fmatrix)) + "\n"
750767

751768

752769
def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):

IPython/utils/timing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
# If possible (Unix), use the resource module instead of time.clock()
2424
try:
2525
import resource
26-
except ImportError:
27-
resource = None
26+
except ModuleNotFoundError:
27+
resource = None # type: ignore [assignment]
2828

2929
# Some implementations (like jyputerlite) don't have getrusage
3030
if resource is not None and hasattr(resource, "getrusage"):

IPython/utils/tokenutil.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88
from keyword import iskeyword
99

1010
import tokenize
11+
from tokenize import TokenInfo
12+
from typing import List, Optional
1113

1214

1315
Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line'])
1416

1517
def generate_tokens(readline):
16-
"""wrap generate_tokens to catch EOF errors"""
18+
"""wrap generate_tkens to catch EOF errors"""
1719
try:
1820
for token in tokenize.generate_tokens(readline):
1921
yield token
@@ -22,7 +24,9 @@ def generate_tokens(readline):
2224
return
2325

2426

25-
def generate_tokens_catch_errors(readline, extra_errors_to_catch=None):
27+
def generate_tokens_catch_errors(
28+
readline, extra_errors_to_catch: Optional[List[str]] = None
29+
):
2630
default_errors_to_catch = [
2731
"unterminated string literal",
2832
"invalid non-printable character",
@@ -31,7 +35,7 @@ def generate_tokens_catch_errors(readline, extra_errors_to_catch=None):
3135
assert extra_errors_to_catch is None or isinstance(extra_errors_to_catch, list)
3236
errors_to_catch = default_errors_to_catch + (extra_errors_to_catch or [])
3337

34-
tokens = []
38+
tokens: List[TokenInfo] = []
3539
try:
3640
for token in tokenize.generate_tokens(readline):
3741
tokens.append(token)
@@ -84,7 +88,8 @@ def line_at_cursor(cell, cursor_pos=0):
8488
line = ""
8589
return (line, offset)
8690

87-
def token_at_cursor(cell, cursor_pos=0):
91+
92+
def token_at_cursor(cell: str, cursor_pos: int = 0):
8893
"""Get the token at a given cursor
8994
9095
Used for introspection.
@@ -94,13 +99,13 @@ def token_at_cursor(cell, cursor_pos=0):
9499
95100
Parameters
96101
----------
97-
cell : unicode
102+
cell : str
98103
A block of Python code
99104
cursor_pos : int
100105
The location of the cursor in the block where the token should be found
101106
"""
102-
names = []
103-
tokens = []
107+
names: List[str] = []
108+
tokens: List[Token] = []
104109
call_names = []
105110

106111
offsets = {1: 0} # lines start at 1

0 commit comments

Comments
 (0)