##// END OF EJS Templates
fix types in utils/text.py
Matthias Bussonnier -
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
@@ -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")
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")
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 = [
@@ -178,11 +178,11 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 NodeTransformer, Store, Load, Name, Expr, Assign, Module, Import, ImportFrom
182 import ast
182 import ast
183 import copy
183 import copy
184
184
185 from typing import Dict, Optional
185 from typing import Dict, Optional, Union
186
186
187
187
188 mangle_all = lambda name: False if name in ("__ret__", "__code__") else True
188 mangle_all = lambda name: False if name in ("__ret__", "__code__") else True
@@ -231,13 +231,13 b' class Mangler(NodeTransformer):'
231 self.log("Not mangling function arg", arg.arg)
231 self.log("Not mangling function arg", arg.arg)
232 return self.generic_visit(node)
232 return self.generic_visit(node)
233
233
234 def visit_ImportFrom(self, node):
234 def visit_ImportFrom(self, node:ImportFrom):
235 return self._visit_Import_and_ImportFrom(node)
235 return self._visit_Import_and_ImportFrom(node)
236
236
237 def visit_Import(self, node):
237 def visit_Import(self, node:Import):
238 return self._visit_Import_and_ImportFrom(node)
238 return self._visit_Import_and_ImportFrom(node)
239
239
240 def _visit_Import_and_ImportFrom(self, node):
240 def _visit_Import_and_ImportFrom(self, node:Union[Import, ImportFrom]):
241 for alias in node.names:
241 for alias in node.names:
242 asname = alias.name if alias.asname is None else alias.asname
242 asname = alias.name if alias.asname is None else alias.asname
243 if self.predicate(asname):
243 if self.predicate(asname):
@@ -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