Skip to content

Commit

Permalink
#1370 added possibility to check X | None on Python >= 3.10
Browse files Browse the repository at this point in the history
  • Loading branch information
JrooTJunior committed Nov 20, 2023
1 parent e17e3bc commit ce4e1a7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
9 changes: 8 additions & 1 deletion aiogram/filters/callback_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import sys
import types
import typing
from decimal import Decimal
from enum import Enum
Expand Down Expand Up @@ -29,6 +31,11 @@
MAX_CALLBACK_LENGTH: int = 64


_UNION_TYPES = {typing.Union}
if sys.version_info >= (3, 10): # pragma: no cover
_UNION_TYPES.add(types.UnionType)


class CallbackDataException(Exception):
pass

Expand Down Expand Up @@ -195,6 +202,6 @@ def _check_field_is_nullable(field: FieldInfo) -> bool:
if not field.is_required():
return True

return typing.get_origin(field.annotation) is typing.Union and type(None) in typing.get_args(
return typing.get_origin(field.annotation) in _UNION_TYPES and type(None) in typing.get_args(
field.annotation
)
11 changes: 11 additions & 0 deletions tests/test_filters/test_callback_data.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from decimal import Decimal
from enum import Enum, auto
from fractions import Fraction
Expand Down Expand Up @@ -163,6 +164,16 @@ class TgData(CallbackData, prefix="tg"):

assert TgData.unpack("tg:123:") == TgData(chat_id=123, thread_id=None)

@pytest.mark.skipif(sys.version_info < (3, 10), reason="UnionType is added in Python 3.10")
def test_unpack_optional_wo_default_union_type(self):
"""Test CallbackData without default optional."""

class TgData(CallbackData, prefix="tg"):
chat_id: int
thread_id: int | None

assert TgData.unpack("tg:123:") == TgData(chat_id=123, thread_id=None)

def test_build_filter(self):
filter_object = MyCallback.filter(F.foo == "test")
assert isinstance(filter_object.rule, MagicFilter)
Expand Down

0 comments on commit ce4e1a7

Please sign in to comment.