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