Skip to content

Commit

Permalink
TYP: Typing hints in pandas/io/formats/{css,csvs}.py
Browse files Browse the repository at this point in the history
  • Loading branch information
MomIsBestFriend committed Dec 22, 2019
1 parent 835f207 commit b7d395a
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 38 deletions.
48 changes: 35 additions & 13 deletions pandas/io/formats/css.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
"""Utilities for interpreting CSS from Stylers for formatting non-HTML outputs
"""
Utilities for interpreting CSS from Stylers for formatting non-HTML outputs.
"""

import re
import warnings


class CSSWarning(UserWarning):
"""This CSS syntax cannot currently be parsed"""
"""
This CSS syntax cannot currently be parsed.
"""

pass


def _side_expander(prop_fmt: str):
def expand(self, prop, value):
"""
Parameters
----------
prop_fmt : str
"""

def expand(self, prop, value: str):
"""
Parameters
----------
prop
value : str
"""
tokens = value.split()
try:
mapping = self.SIDE_SHORTHANDS[len(tokens)]
except KeyError:
warnings.warn(
f'Could not expand "{prop}: {value}"', CSSWarning,
f"Could not expand '{prop}: {value}'", CSSWarning,
)
return
for key, idx in zip(self.SIDES, mapping):
Expand All @@ -28,12 +43,13 @@ def expand(self, prop, value):


class CSSResolver:
"""A callable for parsing and resolving CSS to atomic properties
"""
A callable for parsing and resolving CSS to atomic properties.
"""

def __call__(self, declarations_str, inherited=None):
""" the given declarations to atomic properties
"""
The given declarations to atomic properties.
Parameters
----------
Expand All @@ -46,8 +62,8 @@ def __call__(self, declarations_str, inherited=None):
Returns
-------
props : dict
Atomic CSS 2.2 properties
dict
Atomic CSS 2.2 properties.
Examples
--------
Expand All @@ -69,7 +85,6 @@ def __call__(self, declarations_str, inherited=None):
('font-size', '24pt'),
('font-weight', 'bold')]
"""

props = dict(self.atomize(self.parse(declarations_str)))
if inherited is None:
inherited = {}
Expand Down Expand Up @@ -172,7 +187,9 @@ def __call__(self, declarations_str, inherited=None):

def size_to_pt(self, in_val, em_pt=None, conversions=UNIT_RATIOS):
def _error():
warnings.warn(f"Unhandled size: {repr(in_val)}", CSSWarning)
warnings.warn(
f"Unhandled size: {repr(in_val)}", CSSWarning,
)
return self.size_to_pt("1!!default", conversions=conversions)

try:
Expand Down Expand Up @@ -235,10 +252,15 @@ def atomize(self, declarations):
expand_margin = _side_expander("margin-{:s}")
expand_padding = _side_expander("padding-{:s}")

def parse(self, declarations_str):
"""Generates (prop, value) pairs from declarations
def parse(self, declarations_str: str):
"""
Generates (prop, value) pairs from declarations.
In a future version may generate parsed tokens from tinycss/tinycss2
Parameters
----------
declarations_str : str
"""
for decl in declarations_str.split(";"):
if not decl.strip():
Expand Down
82 changes: 57 additions & 25 deletions pandas/io/formats/csvs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import csv as csvlib
from io import StringIO
import os
from typing import List
from typing import List, Optional, Sequence, Union
import warnings
from zipfile import ZipFile

Expand All @@ -21,6 +21,8 @@
)
from pandas.core.dtypes.missing import notna

from pandas._typing import FilePathOrBuffer

from pandas.io.common import (
get_compression_method,
get_filepath_or_buffer,
Expand All @@ -30,30 +32,54 @@


class CSVFormatter:
r"""
Parameters
----------
obj
path_or_buf : FilePathOrBuffer[str], optional
sep : str, default ','
na_rep : str, default ''
float_format : default None
cols : default None
header : Union[bool, Sequence[str]], default True
index : bool, default True
index_label : default None
mode : str, default 'w'
encoding : str, optional
compression : default 'infer'
quoting : int, optional
line_terminator : str, optional, default '\n'
chunksize : int, optional
quotechar : str, optional, default '"'
date_format : str, optional
doublequote : bool, default True
escapechar : default None
decimal : str, optional, default '.'
"""

def __init__(
self,
obj,
path_or_buf=None,
sep=",",
na_rep="",
path_or_buf: Optional[FilePathOrBuffer[str]] = None,
sep: str = ",",
na_rep: str = "",
float_format=None,
cols=None,
header=True,
index=True,
header: Union[bool, Sequence[str]] = True,
index: bool = True,
index_label=None,
mode="w",
encoding=None,
mode: str = "w",
encoding: Optional[str] = None,
compression="infer",
quoting=None,
line_terminator="\n",
chunksize=None,
quotechar='"',
date_format=None,
doublequote=True,
quoting: Optional[int] = None,
line_terminator: Optional[str] = "\n",
chunksize: Optional[int] = None,
quotechar: Optional[str] = '"',
date_format: Optional[str] = None,
doublequote: bool = True,
escapechar=None,
decimal=".",
decimal: Optional[str] = ".",
):

self.obj = obj

if path_or_buf is None:
Expand Down Expand Up @@ -154,14 +180,17 @@ def __init__(
if not index:
self.nlevels = 0

def save(self):
def save(self) -> None:
"""
Create the writer & save
Create the writer & save.
"""
# GH21227 internal compression is not used when file-like passed.
if self.compression and hasattr(self.path_or_buf, "write"):
msg = "compression has no effect when passing file-like object as input."
warnings.warn(msg, RuntimeWarning, stacklevel=2)
warnings.warn(
"compression has no effect when passing file-like object as input.",
RuntimeWarning,
stacklevel=2,
)

# when zip compression is called.
is_zip = isinstance(self.path_or_buf, ZipFile) or (
Expand Down Expand Up @@ -223,7 +252,6 @@ def save(self):
_fh.close()

def _save_header(self):

writer = self.writer
obj = self.obj
index_label = self.index_label
Expand Down Expand Up @@ -306,8 +334,7 @@ def _save_header(self):
encoded_labels.extend([""] * len(columns))
writer.writerow(encoded_labels)

def _save(self):

def _save(self) -> None:
self._save_header()

nrows = len(self.data_index)
Expand All @@ -324,8 +351,13 @@ def _save(self):

self._save_chunk(start_i, end_i)

def _save_chunk(self, start_i: int, end_i: int):

def _save_chunk(self, start_i: int, end_i: int) -> None:
"""
Parameters
----------
start_i : int
end_i : int
"""
data_index = self.data_index

# create the data for a chunk
Expand Down

0 comments on commit b7d395a

Please sign in to comment.