Skip to content

Commit fcb0c63

Browse files
simonjayhawkinsquintusdias
authored andcommitted
TYPING: add type hints to pandas\io\formats\printing.py (pandas-dev#27579)
1 parent 8979c5b commit fcb0c63

File tree

1 file changed

+49
-38
lines changed

1 file changed

+49
-38
lines changed

pandas/io/formats/printing.py

+49-38
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@
33
"""
44

55
import sys
6+
from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union
67

78
from pandas._config import get_option
89

910
from pandas.core.dtypes.inference import is_sequence
1011

1112

12-
def adjoin(space, *lists, **kwargs):
13+
def adjoin(space: int, *lists: List[str], **kwargs) -> str:
1314
"""
1415
Glues together two sets of strings using the amount of space requested.
1516
The idea is to prettify.
@@ -40,11 +41,11 @@ def adjoin(space, *lists, **kwargs):
4041
newLists.append(nl)
4142
toJoin = zip(*newLists)
4243
for lines in toJoin:
43-
out_lines.append(_join_unicode(lines))
44-
return _join_unicode(out_lines, sep="\n")
44+
out_lines.append("".join(lines))
45+
return "\n".join(out_lines)
4546

4647

47-
def justify(texts, max_len, mode="right"):
48+
def justify(texts: Iterable[str], max_len: int, mode: str = "right") -> List[str]:
4849
"""
4950
Perform ljust, center, rjust against string or list-like
5051
"""
@@ -56,14 +57,6 @@ def justify(texts, max_len, mode="right"):
5657
return [x.rjust(max_len) for x in texts]
5758

5859

59-
def _join_unicode(lines, sep=""):
60-
try:
61-
return sep.join(lines)
62-
except UnicodeDecodeError:
63-
sep = str(sep)
64-
return sep.join([x.decode("utf-8") if isinstance(x, str) else x for x in lines])
65-
66-
6760
# Unicode consolidation
6861
# ---------------------
6962
#
@@ -88,7 +81,9 @@ def _join_unicode(lines, sep=""):
8881
# working with straight ascii.
8982

9083

91-
def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds):
84+
def _pprint_seq(
85+
seq: Sequence, _nest_lvl: int = 0, max_seq_items: Optional[int] = None, **kwds
86+
) -> str:
9287
"""
9388
internal. pprinter for iterables. you should probably use pprint_thing()
9489
rather then calling this directly.
@@ -121,7 +116,9 @@ def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds):
121116
return fmt.format(body=body)
122117

123118

124-
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
119+
def _pprint_dict(
120+
seq: Dict, _nest_lvl: int = 0, max_seq_items: Optional[int] = None, **kwds
121+
) -> str:
125122
"""
126123
internal. pprinter for iterables. you should probably use pprint_thing()
127124
rather then calling this directly.
@@ -152,12 +149,12 @@ def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
152149

153150
def pprint_thing(
154151
thing,
155-
_nest_lvl=0,
156-
escape_chars=None,
157-
default_escapes=False,
158-
quote_strings=False,
159-
max_seq_items=None,
160-
):
152+
_nest_lvl: int = 0,
153+
escape_chars: Optional[Union[Dict[str, str], Iterable[str]]] = None,
154+
default_escapes: bool = False,
155+
quote_strings: bool = False,
156+
max_seq_items: Optional[int] = None,
157+
) -> str:
161158
"""
162159
This function is the sanctioned way of converting objects
163160
to a unicode representation.
@@ -234,12 +231,14 @@ def as_escaped_unicode(thing, escape_chars=escape_chars):
234231
return str(result) # always unicode
235232

236233

237-
def pprint_thing_encoded(object, encoding="utf-8", errors="replace", **kwds):
234+
def pprint_thing_encoded(
235+
object, encoding: str = "utf-8", errors: str = "replace"
236+
) -> bytes:
238237
value = pprint_thing(object) # get unicode representation of object
239-
return value.encode(encoding, errors, **kwds)
238+
return value.encode(encoding, errors)
240239

241240

242-
def _enable_data_resource_formatter(enable):
241+
def _enable_data_resource_formatter(enable: bool) -> None:
243242
if "IPython" not in sys.modules:
244243
# definitely not in IPython
245244
return
@@ -279,12 +278,12 @@ class TableSchemaFormatter(BaseFormatter):
279278

280279
def format_object_summary(
281280
obj,
282-
formatter,
283-
is_justify=True,
284-
name=None,
285-
indent_for_name=True,
286-
line_break_each_value=False,
287-
):
281+
formatter: Callable,
282+
is_justify: bool = True,
283+
name: Optional[str] = None,
284+
indent_for_name: bool = True,
285+
line_break_each_value: bool = False,
286+
) -> str:
288287
"""
289288
Return the formatted obj as a unicode string
290289
@@ -448,7 +447,9 @@ def best_len(values):
448447
return summary
449448

450449

451-
def _justify(head, tail):
450+
def _justify(
451+
head: List[Sequence[str]], tail: List[Sequence[str]]
452+
) -> Tuple[List[Tuple[str, ...]], List[Tuple[str, ...]]]:
452453
"""
453454
Justify items in head and tail, so they are right-aligned when stacked.
454455
@@ -484,10 +485,16 @@ def _justify(head, tail):
484485
tail = [
485486
tuple(x.rjust(max_len) for x, max_len in zip(seq, max_length)) for seq in tail
486487
]
487-
return head, tail
488+
# https://github.com/python/mypy/issues/4975
489+
# error: Incompatible return value type (got "Tuple[List[Sequence[str]],
490+
# List[Sequence[str]]]", expected "Tuple[List[Tuple[str, ...]],
491+
# List[Tuple[str, ...]]]")
492+
return head, tail # type: ignore
488493

489494

490-
def format_object_attrs(obj, include_dtype=True):
495+
def format_object_attrs(
496+
obj: Sequence, include_dtype: bool = True
497+
) -> List[Tuple[str, Union[str, int]]]:
491498
"""
492499
Return a list of tuples of the (attr, formatted_value)
493500
for common attrs, including dtype, name, length
@@ -501,16 +508,20 @@ def format_object_attrs(obj, include_dtype=True):
501508
502509
Returns
503510
-------
504-
list
511+
list of 2-tuple
505512
506513
"""
507-
attrs = []
514+
attrs = [] # type: List[Tuple[str, Union[str, int]]]
508515
if hasattr(obj, "dtype") and include_dtype:
509-
attrs.append(("dtype", "'{}'".format(obj.dtype)))
516+
# error: "Sequence[Any]" has no attribute "dtype"
517+
attrs.append(("dtype", "'{}'".format(obj.dtype))) # type: ignore
510518
if getattr(obj, "name", None) is not None:
511-
attrs.append(("name", default_pprint(obj.name)))
512-
elif getattr(obj, "names", None) is not None and any(obj.names):
513-
attrs.append(("names", default_pprint(obj.names)))
519+
# error: "Sequence[Any]" has no attribute "name"
520+
attrs.append(("name", default_pprint(obj.name))) # type: ignore
521+
# error: "Sequence[Any]" has no attribute "names"
522+
elif getattr(obj, "names", None) is not None and any(obj.names): # type: ignore
523+
# error: "Sequence[Any]" has no attribute "names"
524+
attrs.append(("names", default_pprint(obj.names))) # type: ignore
514525
max_seq_items = get_option("display.max_seq_items") or len(obj)
515526
if len(obj) > max_seq_items:
516527
attrs.append(("length", len(obj)))

0 commit comments

Comments
 (0)