Skip to content

Commit

Permalink
Added suport for Optional[T] in @hybrid_property's type annotation in…
Browse files Browse the repository at this point in the history
…ference. (#343)

Automatic @hybrid_property type conversion now supports Optionals.
  • Loading branch information
flipbit03 authored May 3, 2022
1 parent 0820da7 commit b0aa63c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
12 changes: 12 additions & 0 deletions graphene_sqlalchemy/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,18 @@ def convert_sqlalchemy_hybrid_property_type_time(arg):
return Time


@convert_sqlalchemy_hybrid_property_type.register(lambda x: getattr(x, '__origin__', None) == typing.Union)
def convert_sqlalchemy_hybrid_property_type_option_t(arg):
# Option is actually Union[T, <class NoneType>]

# Just get the T out of the list of arguments by filtering out the NoneType
internal_type = next(filter(lambda x: not type(None) == x, arg.__args__))

graphql_internal_type = convert_sqlalchemy_hybrid_property_type(internal_type)

return graphql_internal_type


@convert_sqlalchemy_hybrid_property_type.register(lambda x: getattr(x, '__origin__', None) in [list, typing.List])
def convert_sqlalchemy_hybrid_property_type_list_t(arg):
# type is either list[T] or List[T], generic argument at __args__[0]
Expand Down
8 changes: 7 additions & 1 deletion graphene_sqlalchemy/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import datetime
import enum
from decimal import Decimal
from typing import List, Tuple
from typing import List, Optional, Tuple

from sqlalchemy import (Column, Date, Enum, ForeignKey, Integer, String, Table,
func, select)
Expand Down Expand Up @@ -217,3 +217,9 @@ def hybrid_prop_self_referential(self) -> 'ShoppingCart':
@hybrid_property
def hybrid_prop_self_referential_list(self) -> List['ShoppingCart']:
return [ShoppingCart(id=1)]

# Optional[T]

@hybrid_property
def hybrid_prop_optional_self_referential(self) -> Optional['ShoppingCart']:
return None
2 changes: 2 additions & 0 deletions graphene_sqlalchemy/tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,8 @@ class Meta:
# Self Referential List
"hybrid_prop_self_referential": ShoppingCartType,
"hybrid_prop_self_referential_list": List(ShoppingCartType),
# Optionals
"hybrid_prop_optional_self_referential": ShoppingCartType,
}

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

0 comments on commit b0aa63c

Please sign in to comment.