File tree Expand file tree Collapse file tree 1 file changed +16
-1
lines changed
Expand file tree Collapse file tree 1 file changed +16
-1
lines changed Original file line number Diff line number Diff line change @@ -97,7 +97,22 @@ def assert_matches_type(
9797 assert_matches_type (key_type , key , path = [* path , "<dict key>" ])
9898 assert_matches_type (items_type , item , path = [* path , "<dict item>" ])
9999 elif is_union_type (type_ ):
100- for i , variant in enumerate (get_args (type_ )):
100+ variants = get_args (type_ )
101+
102+ try :
103+ none_index = variants .index (type (None ))
104+ except ValueError :
105+ pass
106+ else :
107+ # special case Optional[T] for better error messages
108+ if len (variants ) == 2 :
109+ if value is None :
110+ # valid
111+ return
112+
113+ return assert_matches_type (type_ = variants [not none_index ], value = value , path = path )
114+
115+ for i , variant in enumerate (variants ):
101116 try :
102117 assert_matches_type (variant , value , path = [* path , f"variant { i } " ])
103118 return
You can’t perform that action at this time.
0 commit comments