Skip to content

Commit

Permalink
refactor: apply new ruff rules, fix and reformat
Browse files Browse the repository at this point in the history
  • Loading branch information
dangotbanned committed Jun 5, 2024
1 parent 1effcb1 commit a3fd77a
Show file tree
Hide file tree
Showing 48 changed files with 439 additions and 446 deletions.
15 changes: 8 additions & 7 deletions altair/_magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,22 @@ def _prepare_data(data, data_transformers):
elif isinstance(data, str):
return {"url": data}
else:
warnings.warn("data of type {} not recognized".format(type(data)), stacklevel=1)
warnings.warn(f"data of type {type(data)} not recognized", stacklevel=1)
return data


def _get_variable(name):
"""Get a variable from the notebook namespace."""
ip = IPython.get_ipython()
if ip is None:
raise ValueError(
msg = (
"Magic command must be run within an IPython "
"environment, in which get_ipython() is defined."
)
raise ValueError(msg)
if name not in ip.user_ns:
raise NameError(
"argument '{}' does not match the name of any defined variable".format(name)
)
msg = f"argument '{name}' does not match the name of any defined variable"
raise NameError(msg)
return ip.user_ns[name]


Expand Down Expand Up @@ -95,10 +95,11 @@ def vegalite(line, cell):
try:
spec = json.loads(cell)
except json.JSONDecodeError as err:
raise ValueError(
msg = (
"%%vegalite: spec is not valid JSON. "
"Install pyyaml to parse spec as yaml"
) from err
)
raise ValueError(msg) from err
else:
spec = yaml.load(cell, Loader=yaml.SafeLoader)

Expand Down
26 changes: 12 additions & 14 deletions altair/expr/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,51 +184,49 @@ def __getitem__(self, val):

class UnaryExpression(Expression):
def __init__(self, op, val):
super(UnaryExpression, self).__init__(op=op, val=val)
super().__init__(op=op, val=val)

def __repr__(self):
return "({op}{val})".format(op=self.op, val=_js_repr(self.val))
return f"({self.op}{_js_repr(self.val)})"


class BinaryExpression(Expression):
def __init__(self, op, lhs, rhs):
super(BinaryExpression, self).__init__(op=op, lhs=lhs, rhs=rhs)
super().__init__(op=op, lhs=lhs, rhs=rhs)

def __repr__(self):
return "({lhs} {op} {rhs})".format(
op=self.op, lhs=_js_repr(self.lhs), rhs=_js_repr(self.rhs)
)
return f"({_js_repr(self.lhs)} {self.op} {_js_repr(self.rhs)})"


class FunctionExpression(Expression):
def __init__(self, name, args):
super(FunctionExpression, self).__init__(name=name, args=args)
super().__init__(name=name, args=args)

def __repr__(self):
args = ",".join(_js_repr(arg) for arg in self.args)
return "{name}({args})".format(name=self.name, args=args)
return f"{self.name}({args})"


class ConstExpression(Expression):
def __init__(self, name, doc):
self.__doc__ = """{}: {}""".format(name, doc)
super(ConstExpression, self).__init__(name=name, doc=doc)
self.__doc__ = f"""{name}: {doc}"""
super().__init__(name=name, doc=doc)

def __repr__(self):
return str(self.name)


class GetAttrExpression(Expression):
def __init__(self, group, name):
super(GetAttrExpression, self).__init__(group=group, name=name)
super().__init__(group=group, name=name)

def __repr__(self):
return "{}.{}".format(self.group, self.name)
return f"{self.group}.{self.name}"


class GetItemExpression(Expression):
def __init__(self, group, name):
super(GetItemExpression, self).__init__(group=group, name=name)
super().__init__(group=group, name=name)

def __repr__(self):
return "{}[{!r}]".format(self.group, self.name)
return f"{self.group}[{self.name!r}]"
4 changes: 2 additions & 2 deletions altair/expr/funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,13 @@ class ExprFunc:
def __init__(self, name, doc):
self.name = name
self.doc = doc
self.__doc__ = """{}(*args)\n {}""".format(name, doc)
self.__doc__ = f"""{name}(*args)\n {doc}"""

def __call__(self, *args):
return FunctionExpression(self.name, args)

def __repr__(self):
return "<function expr.{}(*args)>".format(self.name)
return f"<function expr.{self.name}(*args)>"


def _populate_namespace():
Expand Down
3 changes: 2 additions & 1 deletion altair/jupyter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
# when anywidget is not installed
class JupyterChart:
def __init__(self, *args, **kwargs):
raise ImportError(
msg = (
"The Altair JupyterChart requires the anywidget \n"
"Python package which may be installed using pip with\n"
" pip install anywidget\n"
"or using conda with\n"
" conda install -c conda-forge anywidget\n"
"Afterwards, you will need to restart your Python kernel."
)
raise ImportError(msg)

else:
from .jupyter_chart import JupyterChart # noqa: F401
9 changes: 6 additions & 3 deletions altair/jupyter/jupyter_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ def __init__(self, trait_values):
elif isinstance(value, IntervalSelection):
traitlet_type = traitlets.Instance(IntervalSelection)
else:
raise ValueError(f"Unexpected selection type: {type(value)}")
msg = f"Unexpected selection type: {type(value)}"
raise ValueError(msg)

# Add the new trait.
self.add_traits(**{key: traitlet_type})
Expand All @@ -82,10 +83,11 @@ def _make_read_only(self, change):
"""
if change["name"] in self.traits() and change["old"] != change["new"]:
self._set_value(change["name"], change["old"])
raise ValueError(
msg = (
"Selections may not be set from Python.\n"
f"Attempted to set select: {change['name']}"
)
raise ValueError(msg)

def _set_value(self, key, value):
self.unobserve(self._make_read_only, names=key)
Expand Down Expand Up @@ -278,7 +280,8 @@ def _on_change_chart(self, change):
name=clean_name, value={}, store=[]
)
else:
raise ValueError(f"Unexpected selection type {select.type}")
msg = f"Unexpected selection type {select.type}"
raise ValueError(msg)
selection_watches.append(clean_name)
initial_vl_selections[clean_name] = {"value": None, "store": []}
else:
Expand Down
6 changes: 0 additions & 6 deletions altair/utils/_dfi_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ def dtype(self) -> Dtype:
- Data types not included: complex, Arrow-style null, binary, decimal,
and nested (list, struct, map, union) dtypes.
"""
pass

# Have to use a generic Any return type as not all libraries who implement
# the dataframe interchange protocol implement the TypedDict that is usually
Expand All @@ -103,7 +102,6 @@ def describe_categorical(self) -> Any:
TBD: are there any other in-memory representations that are needed?
"""
pass


class DataFrame(Protocol):
Expand Down Expand Up @@ -136,19 +134,16 @@ def __dataframe__(
necessary if a library supports strided buffers, given that this protocol
specifies contiguous buffers.
"""
pass

def column_names(self) -> Iterable[str]:
"""
Return an iterator yielding the column names.
"""
pass

def get_column_by_name(self, name: str) -> Column:
"""
Return the column whose name is the indicated name.
"""
pass

def get_chunks(self, n_chunks: Optional[int] = None) -> Iterable["DataFrame"]:
"""
Expand All @@ -162,4 +157,3 @@ def get_chunks(self, n_chunks: Optional[int] = None) -> Iterable["DataFrame"]:
Note that the producer must ensure that all columns are chunked the
same way.
"""
pass
24 changes: 15 additions & 9 deletions altair/utils/_importers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,19 @@ def import_vegafusion() -> ModuleType:
version = importlib_version("vegafusion")
embed_version = importlib_version("vegafusion-python-embed")
if version != embed_version or Version(version) < Version(min_version):
raise RuntimeError(
msg = (
"The versions of the vegafusion and vegafusion-python-embed packages must match\n"
f"and must be version {min_version} or greater.\n"
f"Found:\n"
f" - vegafusion=={version}\n"
f" - vegafusion-python-embed=={embed_version}\n"
)
raise RuntimeError(msg)
import vegafusion as vf # type: ignore

return vf
except ImportError as err:
raise ImportError(
msg = (
'The "vegafusion" data transformer and chart.transformed_data feature requires\n'
f"version {min_version} or greater of the 'vegafusion-python-embed' and 'vegafusion' packages.\n"
"These can be installed with pip using:\n"
Expand All @@ -29,31 +30,34 @@ def import_vegafusion() -> ModuleType:
f' conda install -c conda-forge "vegafusion-python-embed>={min_version}" '
f'"vegafusion>={min_version}"\n\n'
f"ImportError: {err.args[0]}"
) from err
)
raise ImportError(msg) from err


def import_vl_convert() -> ModuleType:
min_version = "1.3.0"
try:
version = importlib_version("vl-convert-python")
if Version(version) < Version(min_version):
raise RuntimeError(
msg = (
f"The vl-convert-python package must be version {min_version} or greater. "
f"Found version {version}"
)
raise RuntimeError(msg)
import vl_convert as vlc

return vlc
except ImportError as err:
raise ImportError(
msg = (
f"The vl-convert Vega-Lite compiler and file export feature requires\n"
f"version {min_version} or greater of the 'vl-convert-python' package. \n"
f"This can be installed with pip using:\n"
f' pip install "vl-convert-python>={min_version}"\n'
"or conda:\n"
f' conda install -c conda-forge "vl-convert-python>={min_version}"\n\n'
f"ImportError: {err.args[0]}"
) from err
)
raise ImportError(msg) from err


def vl_version_for_vl_convert() -> str:
Expand All @@ -70,23 +74,25 @@ def import_pyarrow_interchange() -> ModuleType:
version = importlib_version("pyarrow")

if Version(version) < Version(min_version):
raise RuntimeError(
msg = (
f"The pyarrow package must be version {min_version} or greater. "
f"Found version {version}"
)
raise RuntimeError(msg)
import pyarrow.interchange as pi

return pi
except ImportError as err:
raise ImportError(
msg = (
f"Usage of the DataFrame Interchange Protocol requires\n"
f"version {min_version} or greater of the pyarrow package. \n"
f"This can be installed with pip using:\n"
f' pip install "pyarrow>={min_version}"\n'
"or conda:\n"
f' conda install -c conda-forge "pyarrow>={min_version}"\n\n'
f"ImportError: {err.args[0]}"
) from err
)
raise ImportError(msg) from err


def pyarrow_available() -> bool:
Expand Down
7 changes: 2 additions & 5 deletions altair/utils/_show.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@ def open_html_in_browser(
Port to use. Defaults to a random port
"""
# Encode html to bytes
if isinstance(html, str):
html_bytes = html.encode("utf8")
else:
html_bytes = html
html_bytes = html.encode("utf8") if isinstance(html, str) else html

browser = None

Expand Down Expand Up @@ -69,5 +66,5 @@ def log_message(self, format, *args):
server = HTTPServer(
("127.0.0.1", port if port is not None else 0), OneShotRequestHandler
)
browser.open("http://127.0.0.1:%s" % server.server_port)
browser.open(f"http://127.0.0.1:{server.server_port}")
server.handle_request()
18 changes: 9 additions & 9 deletions altair/utils/_transformed_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,9 @@ def transformed_data(chart, row_limit=None, exclude=None):
transformed data
"""
vf = import_vegafusion()

if isinstance(chart, Chart):
# Add mark if none is specified to satisfy Vega-Lite
if chart.mark == Undefined:
chart = chart.mark_point()
# Add mark if none is specified to satisfy Vega-Lite
if isinstance(chart, Chart) and chart.mark == Undefined:
chart = chart.mark_point()

# Deep copy chart so that we can rename marks without affecting caller
chart = chart.copy(deep=True)
Expand All @@ -119,7 +117,8 @@ def transformed_data(chart, row_limit=None, exclude=None):
if chart_name in dataset_mapping:
dataset_names.append(dataset_mapping[chart_name])
else:
raise ValueError("Failed to locate all datasets")
msg = "Failed to locate all datasets"
raise ValueError(msg)

# Extract transformed datasets with VegaFusion
datasets, warnings = vf.runtime.pre_transform_datasets(
Expand Down Expand Up @@ -200,11 +199,12 @@ def name_views(
elif isinstance(chart, _chart_class_mapping[ConcatChart]):
subcharts = chart.concat
else:
raise ValueError(
msg = (
"transformed_data accepts an instance of "
"Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart\n"
f"Received value of type: {type(chart)}"
)
raise ValueError(msg)

chart_names: List[str] = []
for subchart in subcharts:
Expand Down Expand Up @@ -444,7 +444,7 @@ def get_facet_mapping(group: dict, scope: Scope = ()) -> FacetMapping:
for mark in mark_group.get("marks", []):
if mark.get("type", None) == "group":
# Get facet for this group
group_scope = scope + (group_index,)
group_scope = (*scope, group_index)
facet = mark.get("from", {}).get("facet", None)
if facet is not None:
facet_name = facet.get("name", None)
Expand Down Expand Up @@ -536,7 +536,7 @@ def get_datasets_for_view_names(
name = mark.get("name", "")
if mark.get("type", "") == "group":
group_data_names = get_datasets_for_view_names(
group, vl_chart_names, facet_mapping, scope=scope + (group_index,)
group, vl_chart_names, facet_mapping, scope=(*scope, group_index)
)
for k, v in group_data_names.items():
datasets.setdefault(k, v)
Expand Down
Loading

0 comments on commit a3fd77a

Please sign in to comment.