Skip to content

Commit f41e847

Browse files
committed
Added suport for Optional[T] in @hybrid_property's type annotation inference.
1 parent 0820da7 commit f41e847

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Diff for: graphene_sqlalchemy/converter.py

+12
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,18 @@ def convert_sqlalchemy_hybrid_property_type_time(arg):
331331
return Time
332332

333333

334+
@convert_sqlalchemy_hybrid_property_type.register(lambda x: getattr(x, '__origin__', None) == typing.Union)
335+
def convert_sqlalchemy_hybrid_property_type_option_t(arg):
336+
# Option is actually Union[T, <class NoneType>]
337+
338+
# Just get the T out of the list of arguments by filtering out the NoneType
339+
internal_type = next(filter(lambda x: not type(None) == x, arg.__args__))
340+
341+
graphql_internal_type = convert_sqlalchemy_hybrid_property_type(internal_type)
342+
343+
return graphql_internal_type
344+
345+
334346
@convert_sqlalchemy_hybrid_property_type.register(lambda x: getattr(x, '__origin__', None) in [list, typing.List])
335347
def convert_sqlalchemy_hybrid_property_type_list_t(arg):
336348
# type is either list[T] or List[T], generic argument at __args__[0]

Diff for: graphene_sqlalchemy/tests/models.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import datetime
44
import enum
55
from decimal import Decimal
6-
from typing import List, Tuple
6+
from typing import List, Optional, Tuple
77

88
from sqlalchemy import (Column, Date, Enum, ForeignKey, Integer, String, Table,
99
func, select)
@@ -217,3 +217,9 @@ def hybrid_prop_self_referential(self) -> 'ShoppingCart':
217217
@hybrid_property
218218
def hybrid_prop_self_referential_list(self) -> List['ShoppingCart']:
219219
return [ShoppingCart(id=1)]
220+
221+
# Optional[T]
222+
223+
@hybrid_property
224+
def hybrid_prop_optional_self_referential(self) -> Optional['ShoppingCart']:
225+
return None

Diff for: graphene_sqlalchemy/tests/test_converter.py

+2
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,8 @@ class Meta:
452452
# Self Referential List
453453
"hybrid_prop_self_referential": ShoppingCartType,
454454
"hybrid_prop_self_referential_list": List(ShoppingCartType),
455+
# Optionals
456+
"hybrid_prop_optional_self_referential": ShoppingCartType,
455457
}
456458

457459
assert sorted(list(ShoppingCartType._meta.fields.keys())) == sorted([

0 commit comments

Comments
 (0)