##// END OF EJS Templates
more types, everywhere, and remove some ignored files from mypy. (#14325)
M Bussonnier -
r28644:06d3ec8d merge
parent child Browse files
Show More
@@ -64,7 +64,8 b" magic_run_re = re.compile(r'.*(\\.ipy|\\.ipynb|\\.py[w]?)$')"
64 64 # Local utilities
65 65 #-----------------------------------------------------------------------------
66 66
67 def module_list(path):
67
68 def module_list(path: str) -> List[str]:
68 69 """
69 70 Return the list containing the names of the modules available in the given
70 71 folder.
@@ -80,7 +81,7 b' def module_list(path):'
80 81 # Build a list of all files in the directory and all files
81 82 # in its subdirectories. For performance reasons, do not
82 83 # recurse more than one level into subdirectories.
83 files = []
84 files: List[str] = []
84 85 for root, dirs, nondirs in os.walk(path, followlinks=True):
85 86 subdir = root[len(path)+1:]
86 87 if subdir:
@@ -91,8 +92,8 b' def module_list(path):'
91 92
92 93 else:
93 94 try:
94 files = list(zipimporter(path)._files.keys())
95 except:
95 files = list(zipimporter(path)._files.keys()) # type: ignore
96 except Exception:
96 97 files = []
97 98
98 99 # Build a list of modules which match the import_re regex.
@@ -194,7 +195,9 b' def try_import(mod: str, only_modules=False) -> List[str]:'
194 195
195 196 if m_is_init:
196 197 file_ = m.__file__
197 completions.extend(module_list(os.path.dirname(file_)))
198 file_path = os.path.dirname(file_) # type: ignore
199 if file_path is not None:
200 completions.extend(module_list(file_path))
198 201 completions_set = {c for c in completions if isinstance(c, str)}
199 202 completions_set.discard('__init__')
200 203 return list(completions_set)
@@ -24,7 +24,9 b' from traitlets import List'
24 24 # This used to be defined here - it is imported for backwards compatibility
25 25 from .display_functions import publish_display_data
26 26
27 #-----------------------------------------------------------------------------
27 import typing as t
28
29 # -----------------------------------------------------------------------------
28 30 # Main payload class
29 31 #-----------------------------------------------------------------------------
30 32
@@ -103,9 +105,9 b' class DisplayPublisher(Configurable):'
103 105 rather than creating a new output.
104 106 """
105 107
106 handlers = {}
108 handlers: t.Dict = {}
107 109 if self.shell is not None:
108 handlers = getattr(self.shell, 'mime_renderers', {})
110 handlers = getattr(self.shell, "mime_renderers", {})
109 111
110 112 for mime, handler in handlers.items():
111 113 if mime in data:
@@ -125,11 +127,20 b' class DisplayPublisher(Configurable):'
125 127
126 128 class CapturingDisplayPublisher(DisplayPublisher):
127 129 """A DisplayPublisher that stores"""
128 outputs = List()
129 130
130 def publish(self, data, metadata=None, source=None, *, transient=None, update=False):
131 self.outputs.append({'data':data, 'metadata':metadata,
132 'transient':transient, 'update':update})
131 outputs: List = List()
132
133 def publish(
134 self, data, metadata=None, source=None, *, transient=None, update=False
135 ):
136 self.outputs.append(
137 {
138 "data": data,
139 "metadata": metadata,
140 "transient": transient,
141 "update": update,
142 }
143 )
133 144
134 145 def clear_output(self, wait=False):
135 146 super(CapturingDisplayPublisher, self).clear_output(wait)
@@ -32,25 +32,21 b' This is an handy alias to `ipython history trim --keep=0`'
32 32
33 33 class HistoryTrim(BaseIPythonApplication):
34 34 description = trim_hist_help
35
36 backup = Bool(False,
37 help="Keep the old history file as history.sqlite.<N>"
38 ).tag(config=True)
39
40 keep = Int(1000,
41 help="Number of recent lines to keep in the database."
42 ).tag(config=True)
43
44 flags = Dict(dict(
45 backup = ({'HistoryTrim' : {'backup' : True}},
46 backup.help
47 )
48 ))
49 35
50 aliases=Dict(dict(
51 keep = 'HistoryTrim.keep'
52 ))
53
36 backup = Bool(False, help="Keep the old history file as history.sqlite.<N>").tag(
37 config=True
38 )
39
40 keep = Int(1000, help="Number of recent lines to keep in the database.").tag(
41 config=True
42 )
43
44 flags = Dict( # type: ignore
45 dict(backup=({"HistoryTrim": {"backup": True}}, backup.help))
46 )
47
48 aliases = Dict(dict(keep="HistoryTrim.keep")) # type: ignore
49
54 50 def start(self):
55 51 profile_dir = Path(self.profile_dir.location)
56 52 hist_file = profile_dir / "history.sqlite"
@@ -114,34 +110,33 b' class HistoryTrim(BaseIPythonApplication):'
114 110 print("Backed up longer history file to", backup_hist_file)
115 111 else:
116 112 hist_file.unlink()
117
113
118 114 new_hist_file.rename(hist_file)
119 115
116
120 117 class HistoryClear(HistoryTrim):
121 118 description = clear_hist_help
122 keep = Int(0,
123 help="Number of recent lines to keep in the database.")
124
125 force = Bool(False,
126 help="Don't prompt user for confirmation"
127 ).tag(config=True)
128
129 flags = Dict(dict(
130 force = ({'HistoryClear' : {'force' : True}},
131 force.help),
132 f = ({'HistoryTrim' : {'force' : True}},
133 force.help
119 keep = Int(0, help="Number of recent lines to keep in the database.")
120
121 force = Bool(False, help="Don't prompt user for confirmation").tag(config=True)
122
123 flags = Dict( # type: ignore
124 dict(
125 force=({"HistoryClear": {"force": True}}, force.help),
126 f=({"HistoryTrim": {"force": True}}, force.help),
134 127 )
135 ))
136 aliases = Dict()
128 )
129 aliases = Dict() # type: ignore
137 130
138 131 def start(self):
139 if self.force or ask_yes_no("Really delete all ipython history? ",
140 default="no", interrupt="no"):
132 if self.force or ask_yes_no(
133 "Really delete all ipython history? ", default="no", interrupt="no"
134 ):
141 135 HistoryTrim.start(self)
142 136
137
143 138 class HistoryApp(Application):
144 name = u'ipython-history'
139 name = "ipython-history"
145 140 description = "Manage the IPython history database."
146 141
147 142 subcommands = Dict(dict(
@@ -15,6 +15,7 b' and stores the results.'
15 15
16 16 For more details, see the class docstrings below.
17 17 """
18 from __future__ import annotations
18 19
19 20 from warnings import warn
20 21
@@ -31,7 +32,7 b' import sys'
31 32 import tokenize
32 33 import warnings
33 34
34 from typing import List, Tuple, Union, Optional
35 from typing import List, Tuple, Union, Optional, TYPE_CHECKING
35 36 from types import CodeType
36 37
37 38 from IPython.core.inputtransformer import (leading_indent,
@@ -52,6 +53,8 b' from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP,'
52 53 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,
53 54 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES)
54 55
56 if TYPE_CHECKING:
57 from typing_extensions import Self
55 58 #-----------------------------------------------------------------------------
56 59 # Utilities
57 60 #-----------------------------------------------------------------------------
@@ -637,9 +640,9 b' class IPythonInputSplitter(InputSplitter):'
637 640 # Nothing that calls reset() expects to handle transformer
638 641 # errors
639 642 pass
640
641 def flush_transformers(self):
642 def _flush(transform, outs):
643
644 def flush_transformers(self: Self):
645 def _flush(transform, outs: List[str]):
643 646 """yield transformed lines
644 647
645 648 always strings, never None
@@ -281,13 +281,14 b' class ExecutionInfo(object):'
281 281 )
282 282
283 283
284 class ExecutionResult(object):
284 class ExecutionResult:
285 285 """The result of a call to :meth:`InteractiveShell.run_cell`
286 286
287 287 Stores information about what took place.
288 288 """
289 execution_count = None
290 error_before_exec = None
289
290 execution_count: Optional[int] = None
291 error_before_exec: Optional[bool] = None
291 292 error_in_exec: Optional[BaseException] = None
292 293 info = None
293 294 result = None
@@ -477,7 +478,8 b' class InteractiveShell(SingletonConfigurable):'
477 478 def input_transformers_cleanup(self):
478 479 return self.input_transformer_manager.cleanup_transforms
479 480
480 input_transformers_post = List([],
481 input_transformers_post: List = List(
482 [],
481 483 help="A list of string input transformers, to be applied after IPython's "
482 484 "own input transformations."
483 485 )
@@ -3340,6 +3342,7 b' class InteractiveShell(SingletonConfigurable):'
3340 3342 self.displayhook.exec_result = None
3341 3343
3342 3344 if store_history:
3345 assert self.history_manager is not None
3343 3346 # Write output to the database. Does nothing unless
3344 3347 # history output logging is enabled.
3345 3348 self.history_manager.store_output(self.execution_count)
@@ -26,6 +26,8 b' from ..utils.text import dedent'
26 26 from traitlets import Bool, Dict, Instance, observe
27 27 from logging import error
28 28
29 import typing as t
30
29 31 #-----------------------------------------------------------------------------
30 32 # Globals
31 33 #-----------------------------------------------------------------------------
@@ -36,7 +38,7 b' from logging import error'
36 38 # access to the class when they run. See for more details:
37 39 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
38 40
39 magics = dict(line={}, cell={})
41 magics: t.Dict = dict(line={}, cell={})
40 42
41 43 magic_kinds = ('line', 'cell')
42 44 magic_spec = ('line', 'cell', 'line_cell')
@@ -1,4 +1,3 b''
1 # -*- coding: utf-8 -*-
2 1 """
3 2 Python advanced pretty printer. This pretty printer is intended to
4 3 replace the old `pprint` python module which does not allow developers
@@ -108,6 +107,8 b' from warnings import warn'
108 107 from IPython.utils.decorators import undoc
109 108 from IPython.utils.py3compat import PYPY
110 109
110 from typing import Dict
111
111 112 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
112 113 'for_type', 'for_type_by_name', 'RawText', 'RawStringLiteral', 'CallExpression']
113 114
@@ -807,6 +808,7 b' def _exception_pprint(obj, p, cycle):'
807 808
808 809
809 810 #: the exception base
811 _exception_base: type
810 812 try:
811 813 _exception_base = BaseException
812 814 except NameError:
@@ -848,8 +850,8 b' _type_pprinters[range] = _repr_pprint'
848 850 _type_pprinters[bytes] = _repr_pprint
849 851
850 852 #: printers for types specified by name
851 _deferred_type_pprinters = {
852 }
853 _deferred_type_pprinters: Dict = {}
854
853 855
854 856 def for_type(typ, func):
855 857 """
@@ -17,21 +17,12 b' exclude = ['
17 17 'PyColorize.py',
18 18 '_process_win32_controller.py',
19 19 'IPython/core/application.py',
20 'IPython/core/completerlib.py',
21 'IPython/core/displaypub.py',
22 'IPython/core/historyapp.py',
23 #'IPython/core/interactiveshell.py',
24 'IPython/core/magic.py',
25 20 'IPython/core/profileapp.py',
26 # 'IPython/core/ultratb.py',
27 21 'IPython/lib/deepreload.py',
28 'IPython/lib/pretty.py',
29 22 'IPython/sphinxext/ipython_directive.py',
30 23 'IPython/terminal/ipapp.py',
31 24 'IPython/utils/_process_win32.py',
32 25 'IPython/utils/path.py',
33 'IPython/utils/timing.py',
34 'IPython/utils/text.py'
35 26 ]
36 27
37 28 [tool.pytest.ini_options]
General Comments 0
You need to be logged in to leave comments. Login now