diff --git a/CHANGES/1139.feature.rst b/CHANGES/1139.feature.rst new file mode 100644 index 000000000..3bcc26e12 --- /dev/null +++ b/CHANGES/1139.feature.rst @@ -0,0 +1 @@ +Loosen restriction on integers as query string values to allow classes that implement ``__int__`` -- by :user:`bdraco`. diff --git a/tests/test_update_query.py b/tests/test_update_query.py index 26ccda62a..e652f457e 100644 --- a/tests/test_update_query.py +++ b/tests/test_update_query.py @@ -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 diff --git a/yarl/_url.py b/yarl/_url.py index 22f41da21..b6a4530d1 100644 --- a/yarl/_url.py +++ b/yarl/_url.py @@ -12,6 +12,7 @@ Iterable, Iterator, List, + SupportsInt, Tuple, TypedDict, TypeVar, @@ -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 "