Skip to content

Commit

Permalink
Add missing arguments to Parameter and add type hints (#3173)
Browse files Browse the repository at this point in the history
  • Loading branch information
binste authored Sep 21, 2023
1 parent b2b14cd commit adc6550
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 16 deletions.
1 change: 1 addition & 0 deletions altair/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,7 @@
"TypedFieldDef",
"URI",
"Undefined",
"UndefinedType",
"UnitSpec",
"UnitSpecWithFrame",
"Url",
Expand Down
44 changes: 31 additions & 13 deletions altair/vegalite/v5/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
from toolz.curried import pipe as _pipe
import itertools
import sys
from typing import cast, List, Optional, Any, Iterable
from typing import cast, List, Optional, Any, Iterable, Union, Literal

# Have to rename it here as else it overlaps with schema.core.Type
from typing import Type as TypingType
from typing import Dict as TypingDict

from .schema import core, channels, mixins, Undefined, SCHEMA_URL
from .schema import core, channels, mixins, Undefined, UndefinedType, SCHEMA_URL

from .data import data_transformers
from ... import utils, expr
Expand Down Expand Up @@ -186,26 +186,40 @@ def _get_channels_mapping():
class Parameter(expr.core.OperatorMixin, object):
"""A Parameter object"""

_counter = 0
_counter: int = 0

@classmethod
def _get_name(cls):
def _get_name(cls) -> str:
cls._counter += 1
return f"param_{cls._counter}"

def __init__(self, name):
def __init__(
self,
name: Optional[str] = None,
empty: Union[bool, UndefinedType] = Undefined,
param: Union[
core.VariableParameter,
core.TopLevelSelectionParameter,
core.SelectionParameter,
UndefinedType,
] = Undefined,
param_type: Union[Literal["variable", "selection"], UndefinedType] = Undefined,
) -> None:
if name is None:
name = self._get_name()
self.name = name
self.empty = empty
self.param = param
self.param_type = param_type

@utils.deprecation.deprecated(
message="'ref' is deprecated. No need to call '.ref()' anymore."
)
def ref(self):
def ref(self) -> dict:
"'ref' is deprecated. No need to call '.ref()' anymore."
return self.to_dict()

def to_dict(self):
def to_dict(self) -> TypingDict[str, Union[str, dict]]:
if self.param_type == "variable":
return {"expr": self.name}
elif self.param_type == "selection":
Expand All @@ -214,6 +228,8 @@ def to_dict(self):
if hasattr(self.name, "to_dict")
else self.name
}
else:
raise ValueError(f"Unrecognized parameter type: {self.param_type}")

def __invert__(self):
if self.param_type == "selection":
Expand All @@ -237,16 +253,18 @@ def __or__(self, other):
else:
return expr.core.OperatorMixin.__or__(self, other)

def __repr__(self):
def __repr__(self) -> str:
return "Parameter({0!r}, {1})".format(self.name, self.param)

def _to_expr(self):
def _to_expr(self) -> str:
return self.name

def _from_expr(self, expr):
def _from_expr(self, expr) -> "ParameterExpression":
return ParameterExpression(expr=expr)

def __getattr__(self, field_name):
def __getattr__(
self, field_name: str
) -> Union[expr.core.GetAttrExpression, "SelectionExpression"]:
if field_name.startswith("__") and field_name.endswith("__"):
raise AttributeError(field_name)
_attrexpr = expr.core.GetAttrExpression(self.name, field_name)
Expand All @@ -258,7 +276,7 @@ def __getattr__(self, field_name):

# TODO: Are there any special cases to consider for __getitem__?
# This was copied from v4.
def __getitem__(self, field_name):
def __getitem__(self, field_name: str) -> expr.core.GetItemExpression:
return expr.core.GetItemExpression(self.name, field_name)


Expand Down Expand Up @@ -1726,7 +1744,7 @@ def transform_filter(self, filter, **kwargs) -> Self:
"""
if isinstance(filter, Parameter):
new_filter = {"param": filter.name}
new_filter: TypingDict[str, Union[bool, str]] = {"param": filter.name}
if "empty" in kwargs:
new_filter["empty"] = kwargs.pop("empty")
elif isinstance(filter.empty, bool):
Expand Down
2 changes: 1 addition & 1 deletion altair/vegalite/v5/schema/core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# The contents of this file are automatically written by
# tools/generate_schema_wrapper.py. Do not modify directly.

from altair.utils.schemapi import SchemaBase, Undefined, _subclasses
from altair.utils.schemapi import SchemaBase, Undefined, UndefinedType, _subclasses

import pkgutil
import json
Expand Down
2 changes: 1 addition & 1 deletion tools/generate_schema_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def generate_vegalite_schema_wrapper(schema_file):

contents = [
HEADER,
"from altair.utils.schemapi import SchemaBase, Undefined, _subclasses",
"from altair.utils.schemapi import SchemaBase, Undefined, UndefinedType, _subclasses",
LOAD_SCHEMA.format(schemafile="vega-lite-schema.json"),
]
contents.append(BASE_SCHEMA.format(basename=basename))
Expand Down
3 changes: 2 additions & 1 deletion tools/update_init_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import sys
from pathlib import Path
from os.path import abspath, dirname, join
from typing import TypeVar, Type, cast, List, Any, Optional, Iterable
from typing import TypeVar, Type, cast, List, Any, Optional, Iterable, Union

import black

Expand Down Expand Up @@ -79,6 +79,7 @@ def _is_relevant_attribute(attr_name):
or attr is Literal
or attr is Optional
or attr is Iterable
or attr is Union
or attr_name == "TypingDict"
):
return False
Expand Down

0 comments on commit adc6550

Please sign in to comment.