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