##// END OF EJS Templates
Misc typing and code cleanup. (#14324)
M Bussonnier -
r28629:27b7f552 merge
parent child Browse files
Show More
@@ -30,6 +30,9 b' from .error import UsageError'
30 from traitlets import List, Instance
30 from traitlets import List, Instance
31 from logging import error
31 from logging import error
32
32
33 import typing as t
34
35
33 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
34 # Utilities
37 # Utilities
35 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
@@ -37,7 +40,7 b' from logging import error'
37 # This is used as the pattern for calls to split_user_input.
40 # This is used as the pattern for calls to split_user_input.
38 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
41 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
39
42
40 def default_aliases():
43 def default_aliases() -> t.List[t.Tuple[str, str]]:
41 """Return list of shell aliases to auto-define.
44 """Return list of shell aliases to auto-define.
42 """
45 """
43 # Note: the aliases defined here should be safe to use on a kernel
46 # Note: the aliases defined here should be safe to use on a kernel
@@ -2550,7 +2550,7 b' class IPCompleter(Completer):'
2550 EvaluationContext(
2550 EvaluationContext(
2551 globals=self.global_namespace,
2551 globals=self.global_namespace,
2552 locals=self.namespace,
2552 locals=self.namespace,
2553 evaluation=self.evaluation,
2553 evaluation=self.evaluation, # type: ignore
2554 in_subscript=True,
2554 in_subscript=True,
2555 ),
2555 ),
2556 )
2556 )
@@ -53,20 +53,23 b' class DisplayFormatter(Configurable):'
53 else:
53 else:
54 formatter.enabled = False
54 formatter.enabled = False
55
55
56 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
56 ipython_display_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
57 @default('ipython_display_formatter')
57
58 @default("ipython_display_formatter")
58 def _default_formatter(self):
59 def _default_formatter(self):
59 return IPythonDisplayFormatter(parent=self)
60 return IPythonDisplayFormatter(parent=self)
60
61
61 mimebundle_formatter = ForwardDeclaredInstance('FormatterABC')
62 mimebundle_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
62 @default('mimebundle_formatter')
63
64 @default("mimebundle_formatter")
63 def _default_mime_formatter(self):
65 def _default_mime_formatter(self):
64 return MimeBundleFormatter(parent=self)
66 return MimeBundleFormatter(parent=self)
65
67
66 # A dict of formatter whose keys are format types (MIME types) and whose
68 # A dict of formatter whose keys are format types (MIME types) and whose
67 # values are subclasses of BaseFormatter.
69 # values are subclasses of BaseFormatter.
68 formatters = Dict()
70 formatters = Dict()
69 @default('formatters')
71
72 @default("formatters")
70 def _formatters_default(self):
73 def _formatters_default(self):
71 """Activate the default formatters."""
74 """Activate the default formatters."""
72 formatter_classes = [
75 formatter_classes = [
@@ -490,8 +490,9 b' class HistoryManager(HistoryAccessor):'
490 input_hist_parsed = List([""])
490 input_hist_parsed = List([""])
491 input_hist_raw = List([""])
491 input_hist_raw = List([""])
492 # A list of directories visited during session
492 # A list of directories visited during session
493 dir_hist = List()
493 dir_hist: List = List()
494 @default('dir_hist')
494
495 @default("dir_hist")
495 def _dir_hist_default(self):
496 def _dir_hist_default(self):
496 try:
497 try:
497 return [Path.cwd()]
498 return [Path.cwd()]
@@ -515,8 +516,8 b' class HistoryManager(HistoryAccessor):'
515 "Values of 1 or less effectively disable caching."
516 "Values of 1 or less effectively disable caching."
516 ).tag(config=True)
517 ).tag(config=True)
517 # The input and output caches
518 # The input and output caches
518 db_input_cache = List()
519 db_input_cache: List = List()
519 db_output_cache = List()
520 db_output_cache: List = List()
520
521
521 # History saving in separate thread
522 # History saving in separate thread
522 save_thread = Instance('IPython.core.history.HistorySavingThread',
523 save_thread = Instance('IPython.core.history.HistorySavingThread',
@@ -527,10 +528,10 b' class HistoryManager(HistoryAccessor):'
527 # Variables used to store the three last inputs from the user. On each new
528 # Variables used to store the three last inputs from the user. On each new
528 # history update, we populate the user's namespace with these, shifted as
529 # history update, we populate the user's namespace with these, shifted as
529 # necessary.
530 # necessary.
530 _i00 = Unicode(u'')
531 _i00 = Unicode("")
531 _i = Unicode(u'')
532 _i = Unicode("")
532 _ii = Unicode(u'')
533 _ii = Unicode("")
533 _iii = Unicode(u'')
534 _iii = Unicode("")
534
535
535 # A regex matching all forms of the exit command, so that we don't store
536 # A regex matching all forms of the exit command, so that we don't store
536 # them in the history (it's annoying to rewind the first entry and land on
537 # them in the history (it's annoying to rewind the first entry and land on
@@ -314,11 +314,12 b' class InteractiveShell(SingletonConfigurable):'
314
314
315 _instance = None
315 _instance = None
316
316
317 ast_transformers = List([], help=
317 ast_transformers: List[ast.NodeTransformer] = List(
318 """
318 [],
319 help="""
319 A list of ast.NodeTransformer subclass instances, which will be applied
320 A list of ast.NodeTransformer subclass instances, which will be applied
320 to user input before code is run.
321 to user input before code is run.
321 """
322 """,
322 ).tag(config=True)
323 ).tag(config=True)
323
324
324 autocall = Enum((0,1,2), default_value=0, help=
325 autocall = Enum((0,1,2), default_value=0, help=
@@ -553,14 +554,20 b' class InteractiveShell(SingletonConfigurable):'
553 ).tag(config=True)
554 ).tag(config=True)
554
555
555 # Subcomponents of InteractiveShell
556 # Subcomponents of InteractiveShell
556 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
557 alias_manager = Instance("IPython.core.alias.AliasManager", allow_none=True)
557 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
558 prefilter_manager = Instance(
558 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
559 "IPython.core.prefilter.PrefilterManager", allow_none=True
559 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
560 )
560 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
561 builtin_trap = Instance("IPython.core.builtin_trap.BuiltinTrap")
561 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
562 display_trap = Instance("IPython.core.display_trap.DisplayTrap")
562 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
563 extension_manager = Instance(
563 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
564 "IPython.core.extensions.ExtensionManager", allow_none=True
565 )
566 payload_manager = Instance("IPython.core.payload.PayloadManager", allow_none=True)
567 history_manager = Instance(
568 "IPython.core.history.HistoryAccessorBase", allow_none=True
569 )
570 magics_manager = Instance("IPython.core.magic.MagicsManager")
564
571
565 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
572 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
566 @property
573 @property
@@ -1396,6 +1403,7 b' class InteractiveShell(SingletonConfigurable):'
1396 If new_session is True, a new history session will be opened.
1403 If new_session is True, a new history session will be opened.
1397 """
1404 """
1398 # Clear histories
1405 # Clear histories
1406 assert self.history_manager is not None
1399 self.history_manager.reset(new_session)
1407 self.history_manager.reset(new_session)
1400 # Reset counter used to index all histories
1408 # Reset counter used to index all histories
1401 if new_session:
1409 if new_session:
@@ -1482,6 +1490,7 b' class InteractiveShell(SingletonConfigurable):'
1482 except KeyError as e:
1490 except KeyError as e:
1483 raise NameError("name '%s' is not defined" % varname) from e
1491 raise NameError("name '%s' is not defined" % varname) from e
1484 # Also check in output history
1492 # Also check in output history
1493 assert self.history_manager is not None
1485 ns_refs.append(self.history_manager.output_hist)
1494 ns_refs.append(self.history_manager.output_hist)
1486 for ns in ns_refs:
1495 for ns in ns_refs:
1487 to_delete = [n for n, o in ns.items() if o is obj]
1496 to_delete = [n for n, o in ns.items() if o is obj]
@@ -1801,7 +1810,7 b' class InteractiveShell(SingletonConfigurable):'
1801 """Find an object and return a struct with info about it."""
1810 """Find an object and return a struct with info about it."""
1802 return self._ofind(oname, namespaces)
1811 return self._ofind(oname, namespaces)
1803
1812
1804 def _inspect(self, meth, oname, namespaces=None, **kw):
1813 def _inspect(self, meth, oname: str, namespaces=None, **kw):
1805 """Generic interface to the inspector system.
1814 """Generic interface to the inspector system.
1806
1815
1807 This function is meant to be called by pdef, pdoc & friends.
1816 This function is meant to be called by pdef, pdoc & friends.
@@ -2409,7 +2418,7 b' class InteractiveShell(SingletonConfigurable):'
2409 res = finder(magic_name)
2418 res = finder(magic_name)
2410 return res
2419 return res
2411
2420
2412 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2421 def run_line_magic(self, magic_name: str, line: str, _stack_depth=1):
2413 """Execute the given line magic.
2422 """Execute the given line magic.
2414
2423
2415 Parameters
2424 Parameters
@@ -3256,6 +3265,7 b' class InteractiveShell(SingletonConfigurable):'
3256
3265
3257 # Store raw and processed history
3266 # Store raw and processed history
3258 if store_history:
3267 if store_history:
3268 assert self.history_manager is not None
3259 self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
3269 self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
3260 if not silent:
3270 if not silent:
3261 self.logger.log(cell, raw_cell)
3271 self.logger.log(cell, raw_cell)
@@ -3272,8 +3282,6 b' class InteractiveShell(SingletonConfigurable):'
3272 # compiler
3282 # compiler
3273 compiler = self.compile if shell_futures else self.compiler_class()
3283 compiler = self.compile if shell_futures else self.compiler_class()
3274
3284
3275 _run_async = False
3276
3277 with self.builtin_trap:
3285 with self.builtin_trap:
3278 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
3286 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
3279
3287
@@ -178,11 +178,21 b' transforming:'
178 __skip_doctest__ = True
178 __skip_doctest__ = True
179
179
180
180
181 from ast import NodeTransformer, Store, Load, Name, Expr, Assign, Module
181 from ast import (
182 NodeTransformer,
183 Store,
184 Load,
185 Name,
186 Expr,
187 Assign,
188 Module,
189 Import,
190 ImportFrom,
191 )
182 import ast
192 import ast
183 import copy
193 import copy
184
194
185 from typing import Dict, Optional
195 from typing import Dict, Optional, Union
186
196
187
197
188 mangle_all = lambda name: False if name in ("__ret__", "__code__") else True
198 mangle_all = lambda name: False if name in ("__ret__", "__code__") else True
@@ -231,13 +241,13 b' class Mangler(NodeTransformer):'
231 self.log("Not mangling function arg", arg.arg)
241 self.log("Not mangling function arg", arg.arg)
232 return self.generic_visit(node)
242 return self.generic_visit(node)
233
243
234 def visit_ImportFrom(self, node):
244 def visit_ImportFrom(self, node: ImportFrom):
235 return self._visit_Import_and_ImportFrom(node)
245 return self._visit_Import_and_ImportFrom(node)
236
246
237 def visit_Import(self, node):
247 def visit_Import(self, node: Import):
238 return self._visit_Import_and_ImportFrom(node)
248 return self._visit_Import_and_ImportFrom(node)
239
249
240 def _visit_Import_and_ImportFrom(self, node):
250 def _visit_Import_and_ImportFrom(self, node: Union[Import, ImportFrom]):
241 for alias in node.names:
251 for alias in node.names:
242 asname = alias.name if alias.asname is None else alias.asname
252 asname = alias.name if alias.asname is None else alias.asname
243 if self.predicate(asname):
253 if self.predicate(asname):
@@ -86,7 +86,7 b' class ScriptMagics(Magics):'
86 """
86 """
87 )
87 )
88
88
89 script_magics = List(
89 script_magics: List = List(
90 help="""Extra script cell magics to define
90 help="""Extra script cell magics to define
91
91
92 This generates simple wrappers of `%%script foo` as `%%foo`.
92 This generates simple wrappers of `%%script foo` as `%%foo`.
@@ -95,6 +95,7 b' class ScriptMagics(Magics):'
95 specify them in script_paths
95 specify them in script_paths
96 """,
96 """,
97 ).tag(config=True)
97 ).tag(config=True)
98
98 @default('script_magics')
99 @default('script_magics')
99 def _script_magics_default(self):
100 def _script_magics_default(self):
100 """default to a common list of programs"""
101 """default to a common list of programs"""
@@ -524,11 +524,14 b' class AutocallChecker(PrefilterChecker):'
524
524
525
525
526 class PrefilterHandler(Configurable):
526 class PrefilterHandler(Configurable):
527
527 handler_name = Unicode("normal")
528 handler_name = Unicode('normal')
528 esc_strings: List = List([])
529 esc_strings = List([])
529 shell = Instance(
530 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
530 "IPython.core.interactiveshell.InteractiveShellABC", allow_none=True
531 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
531 )
532 prefilter_manager = Instance(
533 "IPython.core.prefilter.PrefilterManager", allow_none=True
534 )
532
535
533 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
536 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
534 super(PrefilterHandler, self).__init__(
537 super(PrefilterHandler, self).__init__(
@@ -1,4 +1,3 b''
1 # encoding: utf-8
2 """
1 """
3 Utilities for working with strings and text.
2 Utilities for working with strings and text.
4
3
@@ -11,13 +10,12 b' Inheritance diagram:'
11 import os
10 import os
12 import re
11 import re
13 import string
12 import string
14 import sys
15 import textwrap
13 import textwrap
16 import warnings
14 import warnings
17 from string import Formatter
15 from string import Formatter
18 from pathlib import Path
16 from pathlib import Path
19
17
20 from typing import List, Dict, Tuple
18 from typing import List, Dict, Tuple, Optional, cast
21
19
22
20
23 class LSString(str):
21 class LSString(str):
@@ -540,11 +538,12 b' class FullEvalFormatter(Formatter):'
540 """
538 """
541 # copied from Formatter._vformat with minor changes to allow eval
539 # copied from Formatter._vformat with minor changes to allow eval
542 # and replace the format_spec code with slicing
540 # and replace the format_spec code with slicing
543 def vformat(self, format_string:str, args, kwargs)->str:
541 def vformat(self, format_string: str, args, kwargs) -> str:
544 result = []
542 result = []
545 for literal_text, field_name, format_spec, conversion in \
543 conversion: Optional[str]
546 self.parse(format_string):
544 for literal_text, field_name, format_spec, conversion in self.parse(
547
545 format_string
546 ):
548 # output the literal text
547 # output the literal text
549 if literal_text:
548 if literal_text:
550 result.append(literal_text)
549 result.append(literal_text)
@@ -563,7 +562,8 b' class FullEvalFormatter(Formatter):'
563 obj = eval(field_name, kwargs)
562 obj = eval(field_name, kwargs)
564
563
565 # do any conversion on the resulting object
564 # do any conversion on the resulting object
566 obj = self.convert_field(obj, conversion)
565 # type issue in typeshed, fined in https://github.com/python/typeshed/pull/11377
566 obj = self.convert_field(obj, conversion) # type: ignore[arg-type]
567
567
568 # format the object and append to the result
568 # format the object and append to the result
569 result.append(self.format_field(obj, ''))
569 result.append(self.format_field(obj, ''))
@@ -722,7 +722,13 b' def compute_item_matrix('
722 return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
722 return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
723
723
724
724
725 def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=False):
725 def columnize(
726 items: List[str],
727 row_first: bool = False,
728 separator: str = " ",
729 displaywidth: int = 80,
730 spread: bool = False,
731 ):
726 """Transform a list of strings into a single string with columns.
732 """Transform a list of strings into a single string with columns.
727
733
728 Parameters
734 Parameters
@@ -743,7 +749,7 b' def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=Fa'
743 """
749 """
744 warnings.warn(
750 warnings.warn(
745 "`columnize` is Pending Deprecation since IPython 8.17."
751 "`columnize` is Pending Deprecation since IPython 8.17."
746 "It is considered fro removal in in future version. "
752 "It is considered for removal in future versions. "
747 "Please open an issue if you believe it should be kept.",
753 "Please open an issue if you believe it should be kept.",
748 stacklevel=2,
754 stacklevel=2,
749 category=PendingDeprecationWarning,
755 category=PendingDeprecationWarning,
@@ -761,7 +767,7 b' def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=Fa'
761 separator = separator.ljust(int(info["optimal_separator_width"]))
767 separator = separator.ljust(int(info["optimal_separator_width"]))
762 fmatrix: List[filter[int]] = [filter(None, x) for x in matrix]
768 fmatrix: List[filter[int]] = [filter(None, x) for x in matrix]
763 sjoin = lambda x: separator.join(
769 sjoin = lambda x: separator.join(
764 [y.ljust(w, " ") for y, w in zip(x, info["column_widths"])]
770 [y.ljust(w, " ") for y, w in zip(x, cast(List[int], info["column_widths"]))]
765 )
771 )
766 return "\n".join(map(sjoin, fmatrix)) + "\n"
772 return "\n".join(map(sjoin, fmatrix)) + "\n"
767
773
General Comments 0
You need to be logged in to leave comments. Login now