##// END OF EJS Templates
please linter
Matthias Bussonnier -
Show More
@@ -2,13 +2,13 b''
2 # encoding: utf-8
2 # encoding: utf-8
3 """Terminal-based IPython entry point.
3 """Terminal-based IPython entry point.
4 """
4 """
5 #-----------------------------------------------------------------------------
5 # -----------------------------------------------------------------------------
6 # Copyright (c) 2012, IPython Development Team.
6 # Copyright (c) 2012, IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 # -----------------------------------------------------------------------------
12
12
13 from IPython import start_ipython
13 from IPython import start_ipython
14
14
@@ -337,7 +337,7 b' class InputSplitter(object):'
337 # Code object corresponding to the current source. It is automatically
337 # Code object corresponding to the current source. It is automatically
338 # synced to the source, so it can be queried at any time to obtain the code
338 # synced to the source, so it can be queried at any time to obtain the code
339 # object; it will be None if the source doesn't compile to valid Python.
339 # object; it will be None if the source doesn't compile to valid Python.
340 code:Optional[CodeType] = None
340 code: Optional[CodeType] = None
341
341
342 # Private attributes
342 # Private attributes
343
343
@@ -346,9 +346,9 b' class InputSplitter(object):'
346 # Command compiler
346 # Command compiler
347 _compile: codeop.CommandCompiler
347 _compile: codeop.CommandCompiler
348 # Boolean indicating whether the current block is complete
348 # Boolean indicating whether the current block is complete
349 _is_complete:Optional[bool] = None
349 _is_complete: Optional[bool] = None
350 # Boolean indicating whether the current block has an unrecoverable syntax error
350 # Boolean indicating whether the current block has an unrecoverable syntax error
351 _is_invalid:bool = False
351 _is_invalid: bool = False
352
352
353 def __init__(self) -> None:
353 def __init__(self) -> None:
354 """Create a new InputSplitter instance."""
354 """Create a new InputSplitter instance."""
@@ -71,8 +71,8 b' class InputTransformer(metaclass=abc.ABCMeta):'
71 """
71 """
72 @functools.wraps(func)
72 @functools.wraps(func)
73 def transformer_factory(**kwargs):
73 def transformer_factory(**kwargs):
74 return cls(func, **kwargs) # type: ignore [call-arg]
74 return cls(func, **kwargs) # type: ignore [call-arg]
75
75
76 return transformer_factory
76 return transformer_factory
77
77
78 class StatelessInputTransformer(InputTransformer):
78 class StatelessInputTransformer(InputTransformer):
@@ -194,7 +194,7 b' def assemble_logical_lines():'
194 line = ''.join(parts)
194 line = ''.join(parts)
195
195
196 # Utilities
196 # Utilities
197 def _make_help_call(target:str, esc:str, lspace:str) -> str:
197 def _make_help_call(target: str, esc: str, lspace: str) -> str:
198 """Prepares a pinfo(2)/psearch call from a target name and the escape
198 """Prepares a pinfo(2)/psearch call from a target name and the escape
199 (i.e. ? or ??)"""
199 (i.e. ? or ??)"""
200 method = 'pinfo2' if esc == '??' \
200 method = 'pinfo2' if esc == '??' \
@@ -212,17 +212,19 b' def _make_help_call(target:str, esc:str, lspace:str) -> str:'
212
212
213
213
214 # These define the transformations for the different escape characters.
214 # These define the transformations for the different escape characters.
215 def _tr_system(line_info:LineInfo):
215 def _tr_system(line_info: LineInfo):
216 "Translate lines escaped with: !"
216 "Translate lines escaped with: !"
217 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
217 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
218 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
218 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
219
219
220 def _tr_system2(line_info:LineInfo):
220
221 def _tr_system2(line_info: LineInfo):
221 "Translate lines escaped with: !!"
222 "Translate lines escaped with: !!"
222 cmd = line_info.line.lstrip()[2:]
223 cmd = line_info.line.lstrip()[2:]
223 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
224 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
224
225
225 def _tr_help(line_info:LineInfo):
226
227 def _tr_help(line_info: LineInfo):
226 "Translate lines escaped with: ?/??"
228 "Translate lines escaped with: ?/??"
227 # A naked help line should just fire the intro help screen
229 # A naked help line should just fire the intro help screen
228 if not line_info.line[1:]:
230 if not line_info.line[1:]:
@@ -230,7 +232,8 b' def _tr_help(line_info:LineInfo):'
230
232
231 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
233 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
232
234
233 def _tr_magic(line_info:LineInfo):
235
236 def _tr_magic(line_info: LineInfo):
234 "Translate lines escaped with: %"
237 "Translate lines escaped with: %"
235 tpl = '%sget_ipython().run_line_magic(%r, %r)'
238 tpl = '%sget_ipython().run_line_magic(%r, %r)'
236 if line_info.line.startswith(ESC_MAGIC2):
239 if line_info.line.startswith(ESC_MAGIC2):
@@ -241,17 +244,20 b' def _tr_magic(line_info:LineInfo):'
241 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
244 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
242 return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)
245 return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)
243
246
244 def _tr_quote(line_info:LineInfo):
247
248 def _tr_quote(line_info: LineInfo):
245 "Translate lines escaped with: ,"
249 "Translate lines escaped with: ,"
246 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
250 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
247 '", "'.join(line_info.the_rest.split()) )
251 '", "'.join(line_info.the_rest.split()) )
248
252
249 def _tr_quote2(line_info:LineInfo):
253
254 def _tr_quote2(line_info: LineInfo):
250 "Translate lines escaped with: ;"
255 "Translate lines escaped with: ;"
251 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
256 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
252 line_info.the_rest)
257 line_info.the_rest)
253
258
254 def _tr_paren(line_info:LineInfo):
259
260 def _tr_paren(line_info: LineInfo):
255 "Translate lines escaped with: /"
261 "Translate lines escaped with: /"
256 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
262 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
257 ", ".join(line_info.the_rest.split()))
263 ", ".join(line_info.the_rest.split()))
@@ -266,9 +272,8 b' tr = { ESC_SHELL : _tr_system,'
266 ESC_PAREN : _tr_paren }
272 ESC_PAREN : _tr_paren }
267
273
268 @StatelessInputTransformer.wrap
274 @StatelessInputTransformer.wrap
269 def escaped_commands(line:str):
275 def escaped_commands(line: str):
270 """Transform escaped commands - %magic, !system, ?help + various autocalls.
276 """Transform escaped commands - %magic, !system, ?help + various autocalls."""
271 """
272 if not line or line.isspace():
277 if not line or line.isspace():
273 return line
278 return line
274 lineinf = LineInfo(line)
279 lineinf = LineInfo(line)
@@ -342,7 +347,7 b' def ends_in_comment_or_string(src):'
342
347
343
348
344 @StatelessInputTransformer.wrap
349 @StatelessInputTransformer.wrap
345 def help_end(line:str):
350 def help_end(line: str):
346 """Translate lines with ?/?? at the end"""
351 """Translate lines with ?/?? at the end"""
347 m = _help_end_re.search(line)
352 m = _help_end_re.search(line)
348 if m is None or ends_in_comment_or_string(line):
353 if m is None or ends_in_comment_or_string(line):
@@ -357,7 +362,7 b' def help_end(line:str):'
357
362
358
363
359 @CoroutineInputTransformer.wrap
364 @CoroutineInputTransformer.wrap
360 def cellmagic(end_on_blank_line:bool=False):
365 def cellmagic(end_on_blank_line: bool = False):
361 """Captures & transforms cell magics.
366 """Captures & transforms cell magics.
362
367
363 After a cell magic is started, this stores up any lines it gets until it is
368 After a cell magic is started, this stores up any lines it gets until it is
@@ -57,6 +57,7 b' def execfile(fname, glob, loc=None, compiler=None):'
57
57
58 PYPY = platform.python_implementation() == "PyPy"
58 PYPY = platform.python_implementation() == "PyPy"
59
59
60
60 # Cython still rely on that as a Dec 28 2019
61 # Cython still rely on that as a Dec 28 2019
61 # See https://github.com/cython/cython/pull/3291 and
62 # See https://github.com/cython/cython/pull/3291 and
62 # https://github.com/ipython/ipython/issues/12068
63 # https://github.com/ipython/ipython/issues/12068
@@ -629,7 +629,7 b' def _col_chunks(l, max_rows, row_first=False):'
629 yield l[i:(i + max_rows)]
629 yield l[i:(i + max_rows)]
630
630
631
631
632 def _find_optimal(rlist, row_first:bool, separator_size:int, displaywidth:int):
632 def _find_optimal(rlist, row_first: bool, separator_size: int, displaywidth: int):
633 """Calculate optimal info to columnize a list of string"""
633 """Calculate optimal info to columnize a list of string"""
634 for max_rows in range(1, len(rlist) + 1):
634 for max_rows in range(1, len(rlist) + 1):
635 col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
635 col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
@@ -652,7 +652,9 b' def _get_or_default(mylist, i, default=None):'
652 return mylist[i]
652 return mylist[i]
653
653
654
654
655 def compute_item_matrix(items, row_first:bool=False, empty=None,*, separator_size=2, displaywidth=80) -> Tuple[List[List[int]], Dict[str, int]] :
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]]:
656 """Returns a nested list, and info to columnize items
658 """Returns a nested list, and info to columnize items
657
659
658 Parameters
660 Parameters
@@ -707,8 +709,13 b' def compute_item_matrix(items, row_first:bool=False, empty=None,*, separator_si'
707 stacklevel=2,
709 stacklevel=2,
708 category=PendingDeprecationWarning,
710 category=PendingDeprecationWarning,
709 )
711 )
710 info = _find_optimal(list(map(len, items)), row_first, separator_size=separator_size, displaywidth=displaywidth)
712 info = _find_optimal(
711 nrow, ncol = info['max_rows'], info['num_columns']
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"]
712 if row_first:
719 if row_first:
713 return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
720 return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
714 else:
721 else:
@@ -742,14 +749,21 b' def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=Fa'
742 category=PendingDeprecationWarning,
749 category=PendingDeprecationWarning,
743 )
750 )
744 if not items:
751 if not items:
745 return '\n'
752 return "\n"
746 matrix:List[List[int]]
753 matrix: List[List[int]]
747 matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
754 matrix, info = compute_item_matrix(
755 items,
756 row_first=row_first,
757 separator_size=len(separator),
758 displaywidth=displaywidth,
759 )
748 if spread:
760 if spread:
749 separator = separator.ljust(int(info['optimal_separator_width']))
761 separator = separator.ljust(int(info["optimal_separator_width"]))
750 fmatrix:List[filter[int]] = [filter(None, x) for x in matrix]
762 fmatrix: List[filter[int]] = [filter(None, x) for x in matrix]
751 sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
763 sjoin = lambda x: separator.join(
752 return '\n'.join(map(sjoin, fmatrix))+'\n'
764 [y.ljust(w, " ") for y, w in zip(x, info["column_widths"])]
765 )
766 return "\n".join(map(sjoin, fmatrix)) + "\n"
753
767
754
768
755 def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
769 def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
@@ -24,7 +24,7 b' import time'
24 try:
24 try:
25 import resource
25 import resource
26 except ModuleNotFoundError:
26 except ModuleNotFoundError:
27 resource = None #type: ignore [assignment]
27 resource = None # type: ignore [assignment]
28
28
29 # Some implementations (like jyputerlite) don't have getrusage
29 # Some implementations (like jyputerlite) don't have getrusage
30 if resource is not None and hasattr(resource, "getrusage"):
30 if resource is not None and hasattr(resource, "getrusage"):
@@ -24,7 +24,9 b' def generate_tokens(readline):'
24 return
24 return
25
25
26
26
27 def generate_tokens_catch_errors(readline, extra_errors_to_catch:Optional[List[str]]=None):
27 def generate_tokens_catch_errors(
28 readline, extra_errors_to_catch: Optional[List[str]] = None
29 ):
28 default_errors_to_catch = [
30 default_errors_to_catch = [
29 "unterminated string literal",
31 "unterminated string literal",
30 "invalid non-printable character",
32 "invalid non-printable character",
@@ -33,7 +35,7 b' def generate_tokens_catch_errors(readline, extra_errors_to_catch:Optional[List[s'
33 assert extra_errors_to_catch is None or isinstance(extra_errors_to_catch, list)
35 assert extra_errors_to_catch is None or isinstance(extra_errors_to_catch, list)
34 errors_to_catch = default_errors_to_catch + (extra_errors_to_catch or [])
36 errors_to_catch = default_errors_to_catch + (extra_errors_to_catch or [])
35
37
36 tokens:List[TokenInfo] = []
38 tokens: List[TokenInfo] = []
37 try:
39 try:
38 for token in tokenize.generate_tokens(readline):
40 for token in tokenize.generate_tokens(readline):
39 tokens.append(token)
41 tokens.append(token)
@@ -86,7 +88,8 b' def line_at_cursor(cell, cursor_pos=0):'
86 line = ""
88 line = ""
87 return (line, offset)
89 return (line, offset)
88
90
89 def token_at_cursor(cell:str, cursor_pos:int=0):
91
92 def token_at_cursor(cell: str, cursor_pos: int = 0):
90 """Get the token at a given cursor
93 """Get the token at a given cursor
91
94
92 Used for introspection.
95 Used for introspection.
@@ -101,8 +104,8 b' def token_at_cursor(cell:str, cursor_pos:int=0):'
101 cursor_pos : int
104 cursor_pos : int
102 The location of the cursor in the block where the token should be found
105 The location of the cursor in the block where the token should be found
103 """
106 """
104 names:List[str] = []
107 names: List[str] = []
105 tokens:List[Token] = []
108 tokens: List[Token] = []
106 call_names = []
109 call_names = []
107
110
108 offsets = {1: 0} # lines start at 1
111 offsets = {1: 0} # lines start at 1
General Comments 0
You need to be logged in to leave comments. Login now