Skip to content

Commit

Permalink
Accept objects that support __int__ for query vars (#1139)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Sep 9, 2024
1 parent 0ee0104 commit 2340c72
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGES/1139.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Loosen restriction on integers as query string values to allow classes that implement ``__int__`` -- by :user:`bdraco`.
13 changes: 13 additions & 0 deletions tests/test_update_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,19 @@ class IntEnum(int, enum.Enum):
assert str(url2) == "http://example.com/path?a=1"


def test_with_class_that_implements__int__():
"""Allow classes that implement __int__ to be used in query strings."""

class myint:

def __int__(self):
return 84

url = URL("http://example.com/path")
url2 = url.with_query(a=myint())
assert str(url2) == "http://example.com/path?a=84"


def test_with_float_enum():
class FloatEnum(float, enum.Enum):
A = 1.1
Expand Down
5 changes: 2 additions & 3 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
Iterable,
Iterator,
List,
SupportsInt,
Tuple,
TypedDict,
TypeVar,
Expand Down Expand Up @@ -1185,9 +1186,7 @@ def _query_var(v: QueryVariable) -> str:
if math.isnan(v):
raise ValueError("float('nan') is not supported")
return str(float(v))
if cls is not bool and issubclass(cls, int):
if TYPE_CHECKING:
assert isinstance(v, int)
if cls is not bool and isinstance(cls, SupportsInt):
return str(int(v))
raise TypeError(
"Invalid variable type: value "
Expand Down

0 comments on commit 2340c72

Please sign in to comment.