Skip to content

Commit

Permalink
Set correct type when indexing into Var[str] (#2469)
Browse files Browse the repository at this point in the history
* Index into strings

* Write tests
  • Loading branch information
picklelo authored Jan 29, 2024
1 parent b2c749f commit 01c2a1e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
9 changes: 4 additions & 5 deletions reflex/vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,11 +572,10 @@ def __getitem__(self, i: Any) -> Var:
)

# Get the type of the indexed var.
type_ = (
types.get_args(self._var_type)[0]
if types.is_generic_alias(self._var_type)
else Any
)
if types.is_generic_alias(self._var_type):
type_ = types.get_args(self._var_type)[0]
elif types._issubclass(self._var_type, str):
type_ = str

# Use `at` to support negative indices.
return self._replace(
Expand Down
16 changes: 16 additions & 0 deletions tests/test_var.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,22 @@ def test_var_indexing_lists(var):
assert str(var[-1]) == f"{{{var._var_name}.at(-1)}}"


def test_var_indexing_str():
"""Test that we can index into str vars."""
str_var = BaseVar(_var_name="str", _var_type=str)

# Test that indexing gives a type of Var[str].
assert isinstance(str_var[0], Var)
assert str_var[0]._var_type == str

# Test basic indexing.
assert str(str_var[0]) == "{str.at(0)}"
assert str(str_var[1]) == "{str.at(1)}"

# Test negative indexing.
assert str(str_var[-1]) == "{str.at(-1)}"


@pytest.mark.parametrize(
"var, index",
[
Expand Down

0 comments on commit 01c2a1e

Please sign in to comment.