id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
226,100
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.execute_fields
def execute_fields( self, parent_type: GraphQLObjectType, source_value: Any, path: Optional[ResponsePath], fields: Dict[str, List[FieldNode]], ) -> AwaitableOrValue[Dict[str, Any]]: """Execute the given fields concurrently. Implements the "Evaluating selection sets" section of the spec for "read" mode. """ results = {} awaitable_fields: List[str] = [] append_awaitable = awaitable_fields.append for response_name, field_nodes in fields.items(): field_path = add_path(path, response_name) result = self.resolve_field( parent_type, source_value, field_nodes, field_path ) if result is not INVALID: results[response_name] = result if isawaitable(result): append_awaitable(response_name) # If there are no coroutines, we can just return the object if not awaitable_fields: return results # Otherwise, results is a map from field name to the result of resolving that # field, which is possibly a coroutine object. Return a coroutine object that # will yield this same map, but with any coroutines awaited in parallel and # replaced with the values they yielded. async def get_results(): results.update( zip( awaitable_fields, await gather(*(results[field] for field in awaitable_fields)), ) ) return results return get_results()
python
def execute_fields( self, parent_type: GraphQLObjectType, source_value: Any, path: Optional[ResponsePath], fields: Dict[str, List[FieldNode]], ) -> AwaitableOrValue[Dict[str, Any]]: results = {} awaitable_fields: List[str] = [] append_awaitable = awaitable_fields.append for response_name, field_nodes in fields.items(): field_path = add_path(path, response_name) result = self.resolve_field( parent_type, source_value, field_nodes, field_path ) if result is not INVALID: results[response_name] = result if isawaitable(result): append_awaitable(response_name) # If there are no coroutines, we can just return the object if not awaitable_fields: return results # Otherwise, results is a map from field name to the result of resolving that # field, which is possibly a coroutine object. Return a coroutine object that # will yield this same map, but with any coroutines awaited in parallel and # replaced with the values they yielded. async def get_results(): results.update( zip( awaitable_fields, await gather(*(results[field] for field in awaitable_fields)), ) ) return results return get_results()
[ "def", "execute_fields", "(", "self", ",", "parent_type", ":", "GraphQLObjectType", ",", "source_value", ":", "Any", ",", "path", ":", "Optional", "[", "ResponsePath", "]", ",", "fields", ":", "Dict", "[", "str", ",", "List", "[", "FieldNode", "]", "]", ...
Execute the given fields concurrently. Implements the "Evaluating selection sets" section of the spec for "read" mode.
[ "Execute", "the", "given", "fields", "concurrently", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L424-L465
226,101
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.collect_fields
def collect_fields( self, runtime_type: GraphQLObjectType, selection_set: SelectionSetNode, fields: Dict[str, List[FieldNode]], visited_fragment_names: Set[str], ) -> Dict[str, List[FieldNode]]: """Collect fields. Given a selection_set, adds all of the fields in that selection to the passed in map of fields, and returns it at the end. collect_fields requires the "runtime type" of an object. For a field which returns an Interface or Union type, the "runtime type" will be the actual Object type returned by that field. """ for selection in selection_set.selections: if isinstance(selection, FieldNode): if not self.should_include_node(selection): continue name = get_field_entry_key(selection) fields.setdefault(name, []).append(selection) elif isinstance(selection, InlineFragmentNode): if not self.should_include_node( selection ) or not self.does_fragment_condition_match(selection, runtime_type): continue self.collect_fields( runtime_type, selection.selection_set, fields, visited_fragment_names, ) elif isinstance(selection, FragmentSpreadNode): frag_name = selection.name.value if frag_name in visited_fragment_names or not self.should_include_node( selection ): continue visited_fragment_names.add(frag_name) fragment = self.fragments.get(frag_name) if not fragment or not self.does_fragment_condition_match( fragment, runtime_type ): continue self.collect_fields( runtime_type, fragment.selection_set, fields, visited_fragment_names ) return fields
python
def collect_fields( self, runtime_type: GraphQLObjectType, selection_set: SelectionSetNode, fields: Dict[str, List[FieldNode]], visited_fragment_names: Set[str], ) -> Dict[str, List[FieldNode]]: for selection in selection_set.selections: if isinstance(selection, FieldNode): if not self.should_include_node(selection): continue name = get_field_entry_key(selection) fields.setdefault(name, []).append(selection) elif isinstance(selection, InlineFragmentNode): if not self.should_include_node( selection ) or not self.does_fragment_condition_match(selection, runtime_type): continue self.collect_fields( runtime_type, selection.selection_set, fields, visited_fragment_names, ) elif isinstance(selection, FragmentSpreadNode): frag_name = selection.name.value if frag_name in visited_fragment_names or not self.should_include_node( selection ): continue visited_fragment_names.add(frag_name) fragment = self.fragments.get(frag_name) if not fragment or not self.does_fragment_condition_match( fragment, runtime_type ): continue self.collect_fields( runtime_type, fragment.selection_set, fields, visited_fragment_names ) return fields
[ "def", "collect_fields", "(", "self", ",", "runtime_type", ":", "GraphQLObjectType", ",", "selection_set", ":", "SelectionSetNode", ",", "fields", ":", "Dict", "[", "str", ",", "List", "[", "FieldNode", "]", "]", ",", "visited_fragment_names", ":", "Set", "[",...
Collect fields. Given a selection_set, adds all of the fields in that selection to the passed in map of fields, and returns it at the end. collect_fields requires the "runtime type" of an object. For a field which returns an Interface or Union type, the "runtime type" will be the actual Object type returned by that field.
[ "Collect", "fields", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L467-L515
226,102
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.should_include_node
def should_include_node( self, node: Union[FragmentSpreadNode, FieldNode, InlineFragmentNode] ) -> bool: """Check if node should be included Determines if a field should be included based on the @include and @skip directives, where @skip has higher precedence than @include. """ skip = get_directive_values(GraphQLSkipDirective, node, self.variable_values) if skip and skip["if"]: return False include = get_directive_values( GraphQLIncludeDirective, node, self.variable_values ) if include and not include["if"]: return False return True
python
def should_include_node( self, node: Union[FragmentSpreadNode, FieldNode, InlineFragmentNode] ) -> bool: skip = get_directive_values(GraphQLSkipDirective, node, self.variable_values) if skip and skip["if"]: return False include = get_directive_values( GraphQLIncludeDirective, node, self.variable_values ) if include and not include["if"]: return False return True
[ "def", "should_include_node", "(", "self", ",", "node", ":", "Union", "[", "FragmentSpreadNode", ",", "FieldNode", ",", "InlineFragmentNode", "]", ")", "->", "bool", ":", "skip", "=", "get_directive_values", "(", "GraphQLSkipDirective", ",", "node", ",", "self",...
Check if node should be included Determines if a field should be included based on the @include and @skip directives, where @skip has higher precedence than @include.
[ "Check", "if", "node", "should", "be", "included" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L517-L535
226,103
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.does_fragment_condition_match
def does_fragment_condition_match( self, fragment: Union[FragmentDefinitionNode, InlineFragmentNode], type_: GraphQLObjectType, ) -> bool: """Determine if a fragment is applicable to the given type.""" type_condition_node = fragment.type_condition if not type_condition_node: return True conditional_type = type_from_ast(self.schema, type_condition_node) if conditional_type is type_: return True if is_abstract_type(conditional_type): return self.schema.is_possible_type( cast(GraphQLAbstractType, conditional_type), type_ ) return False
python
def does_fragment_condition_match( self, fragment: Union[FragmentDefinitionNode, InlineFragmentNode], type_: GraphQLObjectType, ) -> bool: type_condition_node = fragment.type_condition if not type_condition_node: return True conditional_type = type_from_ast(self.schema, type_condition_node) if conditional_type is type_: return True if is_abstract_type(conditional_type): return self.schema.is_possible_type( cast(GraphQLAbstractType, conditional_type), type_ ) return False
[ "def", "does_fragment_condition_match", "(", "self", ",", "fragment", ":", "Union", "[", "FragmentDefinitionNode", ",", "InlineFragmentNode", "]", ",", "type_", ":", "GraphQLObjectType", ",", ")", "->", "bool", ":", "type_condition_node", "=", "fragment", ".", "ty...
Determine if a fragment is applicable to the given type.
[ "Determine", "if", "a", "fragment", "is", "applicable", "to", "the", "given", "type", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L537-L553
226,104
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.resolve_field
def resolve_field( self, parent_type: GraphQLObjectType, source: Any, field_nodes: List[FieldNode], path: ResponsePath, ) -> AwaitableOrValue[Any]: """Resolve the field on the given source object. In particular, this figures out the value that the field returns by calling its resolve function, then calls complete_value to await coroutine objects, serialize scalars, or execute the sub-selection-set for objects. """ field_node = field_nodes[0] field_name = field_node.name.value field_def = get_field_def(self.schema, parent_type, field_name) if not field_def: return INVALID resolve_fn = field_def.resolve or self.field_resolver if self.middleware_manager: resolve_fn = self.middleware_manager.get_field_resolver(resolve_fn) info = self.build_resolve_info(field_def, field_nodes, parent_type, path) # Get the resolve function, regardless of if its result is normal or abrupt # (error). result = self.resolve_field_value_or_error( field_def, field_nodes, resolve_fn, source, info ) return self.complete_value_catching_error( field_def.type, field_nodes, info, path, result )
python
def resolve_field( self, parent_type: GraphQLObjectType, source: Any, field_nodes: List[FieldNode], path: ResponsePath, ) -> AwaitableOrValue[Any]: field_node = field_nodes[0] field_name = field_node.name.value field_def = get_field_def(self.schema, parent_type, field_name) if not field_def: return INVALID resolve_fn = field_def.resolve or self.field_resolver if self.middleware_manager: resolve_fn = self.middleware_manager.get_field_resolver(resolve_fn) info = self.build_resolve_info(field_def, field_nodes, parent_type, path) # Get the resolve function, regardless of if its result is normal or abrupt # (error). result = self.resolve_field_value_or_error( field_def, field_nodes, resolve_fn, source, info ) return self.complete_value_catching_error( field_def.type, field_nodes, info, path, result )
[ "def", "resolve_field", "(", "self", ",", "parent_type", ":", "GraphQLObjectType", ",", "source", ":", "Any", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "path", ":", "ResponsePath", ",", ")", "->", "AwaitableOrValue", "[", "Any", "]", ":"...
Resolve the field on the given source object. In particular, this figures out the value that the field returns by calling its resolve function, then calls complete_value to await coroutine objects, serialize scalars, or execute the sub-selection-set for objects.
[ "Resolve", "the", "field", "on", "the", "given", "source", "object", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L578-L613
226,105
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.complete_value_catching_error
def complete_value_catching_error( self, return_type: GraphQLOutputType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: """Complete a value while catching an error. This is a small wrapper around completeValue which detects and logs errors in the execution context. """ try: if isawaitable(result): async def await_result(): value = self.complete_value( return_type, field_nodes, info, path, await result ) if isawaitable(value): return await value return value completed = await_result() else: completed = self.complete_value( return_type, field_nodes, info, path, result ) if isawaitable(completed): # noinspection PyShadowingNames async def await_completed(): try: return await completed except Exception as error: self.handle_field_error(error, field_nodes, path, return_type) return await_completed() return completed except Exception as error: self.handle_field_error(error, field_nodes, path, return_type) return None
python
def complete_value_catching_error( self, return_type: GraphQLOutputType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: try: if isawaitable(result): async def await_result(): value = self.complete_value( return_type, field_nodes, info, path, await result ) if isawaitable(value): return await value return value completed = await_result() else: completed = self.complete_value( return_type, field_nodes, info, path, result ) if isawaitable(completed): # noinspection PyShadowingNames async def await_completed(): try: return await completed except Exception as error: self.handle_field_error(error, field_nodes, path, return_type) return await_completed() return completed except Exception as error: self.handle_field_error(error, field_nodes, path, return_type) return None
[ "def", "complete_value_catching_error", "(", "self", ",", "return_type", ":", "GraphQLOutputType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "info", ":", "GraphQLResolveInfo", ",", "path", ":", "ResponsePath", ",", "result", ":", "Any", ",", ...
Complete a value while catching an error. This is a small wrapper around completeValue which detects and logs errors in the execution context.
[ "Complete", "a", "value", "while", "catching", "an", "error", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L648-L689
226,106
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.complete_value
def complete_value( self, return_type: GraphQLOutputType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: """Complete a value. Implements the instructions for completeValue as defined in the "Field entries" section of the spec. If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field error if that completion returns null, as per the "Nullability" section of the spec. If the field type is a List, then this recursively completes the value for the inner type on each item in the list. If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the `serialize` method of GraphQL type definition. If the field is an abstract type, determine the runtime type of the value and then complete based on that type. Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all sub-selections. """ # If result is an Exception, throw a located error. if isinstance(result, Exception): raise result # If field type is NonNull, complete for inner type, and throw field error if # result is null. if is_non_null_type(return_type): completed = self.complete_value( cast(GraphQLNonNull, return_type).of_type, field_nodes, info, path, result, ) if completed is None: raise TypeError( "Cannot return null for non-nullable field" f" {info.parent_type.name}.{info.field_name}." ) return completed # If result value is null-ish (null, INVALID, or NaN) then return null. if is_nullish(result): return None # If field type is List, complete each item in the list with inner type if is_list_type(return_type): return self.complete_list_value( cast(GraphQLList, return_type), field_nodes, info, path, result ) # If field type is a leaf type, Scalar or Enum, serialize to a valid value, # returning null if serialization is not possible. if is_leaf_type(return_type): return self.complete_leaf_value(cast(GraphQLLeafType, return_type), result) # If field type is an abstract type, Interface or Union, determine the runtime # Object type and complete for that type. if is_abstract_type(return_type): return self.complete_abstract_value( cast(GraphQLAbstractType, return_type), field_nodes, info, path, result ) # If field type is Object, execute and complete all sub-selections. if is_object_type(return_type): return self.complete_object_value( cast(GraphQLObjectType, return_type), field_nodes, info, path, result ) # Not reachable. All possible output types have been considered. raise TypeError( # pragma: no cover "Cannot complete value of unexpected output type:" f" '{inspect(return_type)}'." )
python
def complete_value( self, return_type: GraphQLOutputType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: # If result is an Exception, throw a located error. if isinstance(result, Exception): raise result # If field type is NonNull, complete for inner type, and throw field error if # result is null. if is_non_null_type(return_type): completed = self.complete_value( cast(GraphQLNonNull, return_type).of_type, field_nodes, info, path, result, ) if completed is None: raise TypeError( "Cannot return null for non-nullable field" f" {info.parent_type.name}.{info.field_name}." ) return completed # If result value is null-ish (null, INVALID, or NaN) then return null. if is_nullish(result): return None # If field type is List, complete each item in the list with inner type if is_list_type(return_type): return self.complete_list_value( cast(GraphQLList, return_type), field_nodes, info, path, result ) # If field type is a leaf type, Scalar or Enum, serialize to a valid value, # returning null if serialization is not possible. if is_leaf_type(return_type): return self.complete_leaf_value(cast(GraphQLLeafType, return_type), result) # If field type is an abstract type, Interface or Union, determine the runtime # Object type and complete for that type. if is_abstract_type(return_type): return self.complete_abstract_value( cast(GraphQLAbstractType, return_type), field_nodes, info, path, result ) # If field type is Object, execute and complete all sub-selections. if is_object_type(return_type): return self.complete_object_value( cast(GraphQLObjectType, return_type), field_nodes, info, path, result ) # Not reachable. All possible output types have been considered. raise TypeError( # pragma: no cover "Cannot complete value of unexpected output type:" f" '{inspect(return_type)}'." )
[ "def", "complete_value", "(", "self", ",", "return_type", ":", "GraphQLOutputType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "info", ":", "GraphQLResolveInfo", ",", "path", ":", "ResponsePath", ",", "result", ":", "Any", ",", ")", "->", ...
Complete a value. Implements the instructions for completeValue as defined in the "Field entries" section of the spec. If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field error if that completion returns null, as per the "Nullability" section of the spec. If the field type is a List, then this recursively completes the value for the inner type on each item in the list. If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the `serialize` method of GraphQL type definition. If the field is an abstract type, determine the runtime type of the value and then complete based on that type. Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all sub-selections.
[ "Complete", "a", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L709-L791
226,107
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.complete_list_value
def complete_list_value( self, return_type: GraphQLList[GraphQLOutputType], field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Iterable[Any], ) -> AwaitableOrValue[Any]: """Complete a list value. Complete a list value by completing each item in the list with the inner type. """ if not isinstance(result, Iterable) or isinstance(result, str): raise TypeError( "Expected Iterable, but did not find one for field" f" {info.parent_type.name}.{info.field_name}." ) # This is specified as a simple map, however we're optimizing the path where # the list contains no coroutine objects by avoiding creating another coroutine # object. item_type = return_type.of_type awaitable_indices: List[int] = [] append_awaitable = awaitable_indices.append completed_results: List[Any] = [] append_result = completed_results.append for index, item in enumerate(result): # No need to modify the info object containing the path, since from here on # it is not ever accessed by resolver functions. field_path = add_path(path, index) completed_item = self.complete_value_catching_error( item_type, field_nodes, info, field_path, item ) if isawaitable(completed_item): append_awaitable(index) append_result(completed_item) if not awaitable_indices: return completed_results # noinspection PyShadowingNames async def get_completed_results(): for index, result in zip( awaitable_indices, await gather( *(completed_results[index] for index in awaitable_indices) ), ): completed_results[index] = result return completed_results return get_completed_results()
python
def complete_list_value( self, return_type: GraphQLList[GraphQLOutputType], field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Iterable[Any], ) -> AwaitableOrValue[Any]: if not isinstance(result, Iterable) or isinstance(result, str): raise TypeError( "Expected Iterable, but did not find one for field" f" {info.parent_type.name}.{info.field_name}." ) # This is specified as a simple map, however we're optimizing the path where # the list contains no coroutine objects by avoiding creating another coroutine # object. item_type = return_type.of_type awaitable_indices: List[int] = [] append_awaitable = awaitable_indices.append completed_results: List[Any] = [] append_result = completed_results.append for index, item in enumerate(result): # No need to modify the info object containing the path, since from here on # it is not ever accessed by resolver functions. field_path = add_path(path, index) completed_item = self.complete_value_catching_error( item_type, field_nodes, info, field_path, item ) if isawaitable(completed_item): append_awaitable(index) append_result(completed_item) if not awaitable_indices: return completed_results # noinspection PyShadowingNames async def get_completed_results(): for index, result in zip( awaitable_indices, await gather( *(completed_results[index] for index in awaitable_indices) ), ): completed_results[index] = result return completed_results return get_completed_results()
[ "def", "complete_list_value", "(", "self", ",", "return_type", ":", "GraphQLList", "[", "GraphQLOutputType", "]", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "info", ":", "GraphQLResolveInfo", ",", "path", ":", "ResponsePath", ",", "result", "...
Complete a list value. Complete a list value by completing each item in the list with the inner type.
[ "Complete", "a", "list", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L793-L845
226,108
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.complete_leaf_value
def complete_leaf_value(return_type: GraphQLLeafType, result: Any) -> Any: """Complete a leaf value. Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible. """ serialized_result = return_type.serialize(result) if is_invalid(serialized_result): raise TypeError( f"Expected a value of type '{inspect(return_type)}'" f" but received: {inspect(result)}" ) return serialized_result
python
def complete_leaf_value(return_type: GraphQLLeafType, result: Any) -> Any: serialized_result = return_type.serialize(result) if is_invalid(serialized_result): raise TypeError( f"Expected a value of type '{inspect(return_type)}'" f" but received: {inspect(result)}" ) return serialized_result
[ "def", "complete_leaf_value", "(", "return_type", ":", "GraphQLLeafType", ",", "result", ":", "Any", ")", "->", "Any", ":", "serialized_result", "=", "return_type", ".", "serialize", "(", "result", ")", "if", "is_invalid", "(", "serialized_result", ")", ":", "...
Complete a leaf value. Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible.
[ "Complete", "a", "leaf", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L848-L860
226,109
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.complete_abstract_value
def complete_abstract_value( self, return_type: GraphQLAbstractType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: """Complete an abstract value. Complete a value of an abstract type by determining the runtime object type of that value, then complete the value for that type. """ resolve_type_fn = return_type.resolve_type or self.type_resolver runtime_type = resolve_type_fn(result, info, return_type) # type: ignore if isawaitable(runtime_type): async def await_complete_object_value(): value = self.complete_object_value( self.ensure_valid_runtime_type( await runtime_type, return_type, field_nodes, info, result ), field_nodes, info, path, result, ) if isawaitable(value): return await value return value return await_complete_object_value() runtime_type = cast(Optional[Union[GraphQLObjectType, str]], runtime_type) return self.complete_object_value( self.ensure_valid_runtime_type( runtime_type, return_type, field_nodes, info, result ), field_nodes, info, path, result, )
python
def complete_abstract_value( self, return_type: GraphQLAbstractType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Any]: resolve_type_fn = return_type.resolve_type or self.type_resolver runtime_type = resolve_type_fn(result, info, return_type) # type: ignore if isawaitable(runtime_type): async def await_complete_object_value(): value = self.complete_object_value( self.ensure_valid_runtime_type( await runtime_type, return_type, field_nodes, info, result ), field_nodes, info, path, result, ) if isawaitable(value): return await value return value return await_complete_object_value() runtime_type = cast(Optional[Union[GraphQLObjectType, str]], runtime_type) return self.complete_object_value( self.ensure_valid_runtime_type( runtime_type, return_type, field_nodes, info, result ), field_nodes, info, path, result, )
[ "def", "complete_abstract_value", "(", "self", ",", "return_type", ":", "GraphQLAbstractType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "info", ":", "GraphQLResolveInfo", ",", "path", ":", "ResponsePath", ",", "result", ":", "Any", ",", ")"...
Complete an abstract value. Complete a value of an abstract type by determining the runtime object type of that value, then complete the value for that type.
[ "Complete", "an", "abstract", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L862-L905
226,110
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.complete_object_value
def complete_object_value( self, return_type: GraphQLObjectType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Dict[str, Any]]: """Complete an Object value by executing all sub-selections.""" # If there is an `is_type_of()` predicate function, call it with the current # result. If `is_type_of()` returns False, then raise an error rather than # continuing execution. if return_type.is_type_of: is_type_of = return_type.is_type_of(result, info) if isawaitable(is_type_of): async def collect_and_execute_subfields_async(): if not await is_type_of: raise invalid_return_type_error( return_type, result, field_nodes ) return self.collect_and_execute_subfields( return_type, field_nodes, path, result ) return collect_and_execute_subfields_async() if not is_type_of: raise invalid_return_type_error(return_type, result, field_nodes) return self.collect_and_execute_subfields( return_type, field_nodes, path, result )
python
def complete_object_value( self, return_type: GraphQLObjectType, field_nodes: List[FieldNode], info: GraphQLResolveInfo, path: ResponsePath, result: Any, ) -> AwaitableOrValue[Dict[str, Any]]: # If there is an `is_type_of()` predicate function, call it with the current # result. If `is_type_of()` returns False, then raise an error rather than # continuing execution. if return_type.is_type_of: is_type_of = return_type.is_type_of(result, info) if isawaitable(is_type_of): async def collect_and_execute_subfields_async(): if not await is_type_of: raise invalid_return_type_error( return_type, result, field_nodes ) return self.collect_and_execute_subfields( return_type, field_nodes, path, result ) return collect_and_execute_subfields_async() if not is_type_of: raise invalid_return_type_error(return_type, result, field_nodes) return self.collect_and_execute_subfields( return_type, field_nodes, path, result )
[ "def", "complete_object_value", "(", "self", ",", "return_type", ":", "GraphQLObjectType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "info", ":", "GraphQLResolveInfo", ",", "path", ":", "ResponsePath", ",", "result", ":", "Any", ",", ")", ...
Complete an Object value by executing all sub-selections.
[ "Complete", "an", "Object", "value", "by", "executing", "all", "sub", "-", "selections", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L943-L976
226,111
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.collect_and_execute_subfields
def collect_and_execute_subfields( self, return_type: GraphQLObjectType, field_nodes: List[FieldNode], path: ResponsePath, result: Any, ) -> AwaitableOrValue[Dict[str, Any]]: """Collect sub-fields to execute to complete this value.""" sub_field_nodes = self.collect_subfields(return_type, field_nodes) return self.execute_fields(return_type, result, path, sub_field_nodes)
python
def collect_and_execute_subfields( self, return_type: GraphQLObjectType, field_nodes: List[FieldNode], path: ResponsePath, result: Any, ) -> AwaitableOrValue[Dict[str, Any]]: sub_field_nodes = self.collect_subfields(return_type, field_nodes) return self.execute_fields(return_type, result, path, sub_field_nodes)
[ "def", "collect_and_execute_subfields", "(", "self", ",", "return_type", ":", "GraphQLObjectType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ",", "path", ":", "ResponsePath", ",", "result", ":", "Any", ",", ")", "->", "AwaitableOrValue", "[", "Di...
Collect sub-fields to execute to complete this value.
[ "Collect", "sub", "-", "fields", "to", "execute", "to", "complete", "this", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L978-L987
226,112
graphql-python/graphql-core-next
graphql/execution/execute.py
ExecutionContext.collect_subfields
def collect_subfields( self, return_type: GraphQLObjectType, field_nodes: List[FieldNode] ) -> Dict[str, List[FieldNode]]: """Collect subfields. A cached collection of relevant subfields with regard to the return type is kept in the execution context as `_subfields_cache`. This ensures the subfields are not repeatedly calculated, which saves overhead when resolving lists of values. """ cache_key = return_type, tuple(field_nodes) sub_field_nodes = self._subfields_cache.get(cache_key) if sub_field_nodes is None: sub_field_nodes = {} visited_fragment_names: Set[str] = set() for field_node in field_nodes: selection_set = field_node.selection_set if selection_set: sub_field_nodes = self.collect_fields( return_type, selection_set, sub_field_nodes, visited_fragment_names, ) self._subfields_cache[cache_key] = sub_field_nodes return sub_field_nodes
python
def collect_subfields( self, return_type: GraphQLObjectType, field_nodes: List[FieldNode] ) -> Dict[str, List[FieldNode]]: cache_key = return_type, tuple(field_nodes) sub_field_nodes = self._subfields_cache.get(cache_key) if sub_field_nodes is None: sub_field_nodes = {} visited_fragment_names: Set[str] = set() for field_node in field_nodes: selection_set = field_node.selection_set if selection_set: sub_field_nodes = self.collect_fields( return_type, selection_set, sub_field_nodes, visited_fragment_names, ) self._subfields_cache[cache_key] = sub_field_nodes return sub_field_nodes
[ "def", "collect_subfields", "(", "self", ",", "return_type", ":", "GraphQLObjectType", ",", "field_nodes", ":", "List", "[", "FieldNode", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "FieldNode", "]", "]", ":", "cache_key", "=", "return_type", ","...
Collect subfields. A cached collection of relevant subfields with regard to the return type is kept in the execution context as `_subfields_cache`. This ensures the subfields are not repeatedly calculated, which saves overhead when resolving lists of values.
[ "Collect", "subfields", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L989-L1014
226,113
graphql-python/graphql-core-next
graphql/utilities/get_operation_root_type.py
get_operation_root_type
def get_operation_root_type( schema: GraphQLSchema, operation: Union[OperationDefinitionNode, OperationTypeDefinitionNode], ) -> GraphQLObjectType: """Extract the root type of the operation from the schema.""" operation_type = operation.operation if operation_type == OperationType.QUERY: query_type = schema.query_type if not query_type: raise GraphQLError( "Schema does not define the required query root type.", operation ) return query_type elif operation_type == OperationType.MUTATION: mutation_type = schema.mutation_type if not mutation_type: raise GraphQLError("Schema is not configured for mutations.", operation) return mutation_type elif operation_type == OperationType.SUBSCRIPTION: subscription_type = schema.subscription_type if not subscription_type: raise GraphQLError("Schema is not configured for subscriptions.", operation) return subscription_type else: raise GraphQLError( "Can only have query, mutation and subscription operations.", operation )
python
def get_operation_root_type( schema: GraphQLSchema, operation: Union[OperationDefinitionNode, OperationTypeDefinitionNode], ) -> GraphQLObjectType: operation_type = operation.operation if operation_type == OperationType.QUERY: query_type = schema.query_type if not query_type: raise GraphQLError( "Schema does not define the required query root type.", operation ) return query_type elif operation_type == OperationType.MUTATION: mutation_type = schema.mutation_type if not mutation_type: raise GraphQLError("Schema is not configured for mutations.", operation) return mutation_type elif operation_type == OperationType.SUBSCRIPTION: subscription_type = schema.subscription_type if not subscription_type: raise GraphQLError("Schema is not configured for subscriptions.", operation) return subscription_type else: raise GraphQLError( "Can only have query, mutation and subscription operations.", operation )
[ "def", "get_operation_root_type", "(", "schema", ":", "GraphQLSchema", ",", "operation", ":", "Union", "[", "OperationDefinitionNode", ",", "OperationTypeDefinitionNode", "]", ",", ")", "->", "GraphQLObjectType", ":", "operation_type", "=", "operation", ".", "operatio...
Extract the root type of the operation from the schema.
[ "Extract", "the", "root", "type", "of", "the", "operation", "from", "the", "schema", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/get_operation_root_type.py#L14-L40
226,114
graphql-python/graphql-core-next
graphql/type/directives.py
is_specified_directive
def is_specified_directive(directive: GraphQLDirective): """Check whether the given directive is one of the specified directives.""" return isinstance(directive, GraphQLDirective) and any( specified_directive.name == directive.name for specified_directive in specified_directives )
python
def is_specified_directive(directive: GraphQLDirective): return isinstance(directive, GraphQLDirective) and any( specified_directive.name == directive.name for specified_directive in specified_directives )
[ "def", "is_specified_directive", "(", "directive", ":", "GraphQLDirective", ")", ":", "return", "isinstance", "(", "directive", ",", "GraphQLDirective", ")", "and", "any", "(", "specified_directive", ".", "name", "==", "directive", ".", "name", "for", "specified_d...
Check whether the given directive is one of the specified directives.
[ "Check", "whether", "the", "given", "directive", "is", "one", "of", "the", "specified", "directives", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/directives.py#L176-L181
226,115
graphql-python/graphql-core-next
graphql/error/print_error.py
print_error
def print_error(error: "GraphQLError") -> str: """Print a GraphQLError to a string. The printed string will contain useful location information about the error's position in the source. """ printed_locations: List[str] = [] print_location = printed_locations.append if error.nodes: for node in error.nodes: if node.loc: print_location( highlight_source_at_location( node.loc.source, node.loc.source.get_location(node.loc.start) ) ) elif error.source and error.locations: source = error.source for location in error.locations: print_location(highlight_source_at_location(source, location)) if printed_locations: return "\n\n".join([error.message] + printed_locations) + "\n" return error.message
python
def print_error(error: "GraphQLError") -> str: printed_locations: List[str] = [] print_location = printed_locations.append if error.nodes: for node in error.nodes: if node.loc: print_location( highlight_source_at_location( node.loc.source, node.loc.source.get_location(node.loc.start) ) ) elif error.source and error.locations: source = error.source for location in error.locations: print_location(highlight_source_at_location(source, location)) if printed_locations: return "\n\n".join([error.message] + printed_locations) + "\n" return error.message
[ "def", "print_error", "(", "error", ":", "\"GraphQLError\"", ")", "->", "str", ":", "printed_locations", ":", "List", "[", "str", "]", "=", "[", "]", "print_location", "=", "printed_locations", ".", "append", "if", "error", ".", "nodes", ":", "for", "node"...
Print a GraphQLError to a string. The printed string will contain useful location information about the error's position in the source.
[ "Print", "a", "GraphQLError", "to", "a", "string", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/error/print_error.py#L13-L35
226,116
graphql-python/graphql-core-next
graphql/error/print_error.py
highlight_source_at_location
def highlight_source_at_location(source: "Source", location: "SourceLocation") -> str: """Highlight source at given location. This renders a helpful description of the location of the error in the GraphQL Source document. """ first_line_column_offset = source.location_offset.column - 1 body = " " * first_line_column_offset + source.body line_index = location.line - 1 line_offset = source.location_offset.line - 1 line_num = location.line + line_offset column_offset = first_line_column_offset if location.line == 1 else 0 column_num = location.column + column_offset lines = _re_newline.split(body) # works a bit different from splitlines() len_lines = len(lines) def get_line(index: int) -> Optional[str]: return lines[index] if 0 <= index < len_lines else None return f"{source.name} ({line_num}:{column_num})\n" + print_prefixed_lines( [ (f"{line_num - 1}: ", get_line(line_index - 1)), (f"{line_num}: ", get_line(line_index)), ("", " " * (column_num - 1) + "^"), (f"{line_num + 1}: ", get_line(line_index + 1)), ] )
python
def highlight_source_at_location(source: "Source", location: "SourceLocation") -> str: first_line_column_offset = source.location_offset.column - 1 body = " " * first_line_column_offset + source.body line_index = location.line - 1 line_offset = source.location_offset.line - 1 line_num = location.line + line_offset column_offset = first_line_column_offset if location.line == 1 else 0 column_num = location.column + column_offset lines = _re_newline.split(body) # works a bit different from splitlines() len_lines = len(lines) def get_line(index: int) -> Optional[str]: return lines[index] if 0 <= index < len_lines else None return f"{source.name} ({line_num}:{column_num})\n" + print_prefixed_lines( [ (f"{line_num - 1}: ", get_line(line_index - 1)), (f"{line_num}: ", get_line(line_index)), ("", " " * (column_num - 1) + "^"), (f"{line_num + 1}: ", get_line(line_index + 1)), ] )
[ "def", "highlight_source_at_location", "(", "source", ":", "\"Source\"", ",", "location", ":", "\"SourceLocation\"", ")", "->", "str", ":", "first_line_column_offset", "=", "source", ".", "location_offset", ".", "column", "-", "1", "body", "=", "\" \"", "*", "fi...
Highlight source at given location. This renders a helpful description of the location of the error in the GraphQL Source document.
[ "Highlight", "source", "at", "given", "location", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/error/print_error.py#L41-L70
226,117
graphql-python/graphql-core-next
graphql/pyutils/inspect.py
trunc_str
def trunc_str(s: str) -> str: """Truncate strings to maximum length.""" if len(s) > max_str_size: i = max(0, (max_str_size - 3) // 2) j = max(0, max_str_size - 3 - i) s = s[:i] + "..." + s[-j:] return s
python
def trunc_str(s: str) -> str: if len(s) > max_str_size: i = max(0, (max_str_size - 3) // 2) j = max(0, max_str_size - 3 - i) s = s[:i] + "..." + s[-j:] return s
[ "def", "trunc_str", "(", "s", ":", "str", ")", "->", "str", ":", "if", "len", "(", "s", ")", ">", "max_str_size", ":", "i", "=", "max", "(", "0", ",", "(", "max_str_size", "-", "3", ")", "//", "2", ")", "j", "=", "max", "(", "0", ",", "max_...
Truncate strings to maximum length.
[ "Truncate", "strings", "to", "maximum", "length", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/inspect.py#L148-L154
226,118
graphql-python/graphql-core-next
graphql/pyutils/inspect.py
trunc_list
def trunc_list(s: List) -> List: """Truncate lists to maximum length.""" if len(s) > max_list_size: i = max_list_size // 2 j = i - 1 s = s[:i] + [ELLIPSIS] + s[-j:] return s
python
def trunc_list(s: List) -> List: if len(s) > max_list_size: i = max_list_size // 2 j = i - 1 s = s[:i] + [ELLIPSIS] + s[-j:] return s
[ "def", "trunc_list", "(", "s", ":", "List", ")", "->", "List", ":", "if", "len", "(", "s", ")", ">", "max_list_size", ":", "i", "=", "max_list_size", "//", "2", "j", "=", "i", "-", "1", "s", "=", "s", "[", ":", "i", "]", "+", "[", "ELLIPSIS",...
Truncate lists to maximum length.
[ "Truncate", "lists", "to", "maximum", "length", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/inspect.py#L157-L163
226,119
graphql-python/graphql-core-next
graphql/language/block_string.py
dedent_block_string_value
def dedent_block_string_value(raw_string: str) -> str: """Produce the value of a block string from its parsed raw value. Similar to CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. This implements the GraphQL spec's BlockStringValue() static algorithm. """ lines = raw_string.splitlines() common_indent = None for line in lines[1:]: indent = leading_whitespace(line) if indent < len(line) and (common_indent is None or indent < common_indent): common_indent = indent if common_indent == 0: break if common_indent: lines[1:] = [line[common_indent:] for line in lines[1:]] while lines and not lines[0].strip(): lines = lines[1:] while lines and not lines[-1].strip(): lines = lines[:-1] return "\n".join(lines)
python
def dedent_block_string_value(raw_string: str) -> str: lines = raw_string.splitlines() common_indent = None for line in lines[1:]: indent = leading_whitespace(line) if indent < len(line) and (common_indent is None or indent < common_indent): common_indent = indent if common_indent == 0: break if common_indent: lines[1:] = [line[common_indent:] for line in lines[1:]] while lines and not lines[0].strip(): lines = lines[1:] while lines and not lines[-1].strip(): lines = lines[:-1] return "\n".join(lines)
[ "def", "dedent_block_string_value", "(", "raw_string", ":", "str", ")", "->", "str", ":", "lines", "=", "raw_string", ".", "splitlines", "(", ")", "common_indent", "=", "None", "for", "line", "in", "lines", "[", "1", ":", "]", ":", "indent", "=", "leadin...
Produce the value of a block string from its parsed raw value. Similar to CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. This implements the GraphQL spec's BlockStringValue() static algorithm.
[ "Produce", "the", "value", "of", "a", "block", "string", "from", "its", "parsed", "raw", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/block_string.py#L4-L31
226,120
graphql-python/graphql-core-next
graphql/language/block_string.py
print_block_string
def print_block_string( value: str, indentation: str = "", prefer_multiple_lines: bool = False ) -> str: """Print a block string in the indented block form. Prints a block string in the indented block form by adding a leading and trailing blank line. However, if a block string starts with whitespace and is a single-line, adding a leading blank line would strip that whitespace. """ is_single_line = "\n" not in value has_leading_space = value.startswith(" ") or value.startswith("\t") has_trailing_quote = value.endswith('"') print_as_multiple_lines = ( not is_single_line or has_trailing_quote or prefer_multiple_lines ) # Format a multi-line block quote to account for leading space. if print_as_multiple_lines and not (is_single_line and has_leading_space): result = "\n" + indentation else: result = "" result += value.replace("\n", "\n" + indentation) if indentation else value if print_as_multiple_lines: result += "\n" return '"""' + result.replace('"""', '\\"""') + '"""'
python
def print_block_string( value: str, indentation: str = "", prefer_multiple_lines: bool = False ) -> str: is_single_line = "\n" not in value has_leading_space = value.startswith(" ") or value.startswith("\t") has_trailing_quote = value.endswith('"') print_as_multiple_lines = ( not is_single_line or has_trailing_quote or prefer_multiple_lines ) # Format a multi-line block quote to account for leading space. if print_as_multiple_lines and not (is_single_line and has_leading_space): result = "\n" + indentation else: result = "" result += value.replace("\n", "\n" + indentation) if indentation else value if print_as_multiple_lines: result += "\n" return '"""' + result.replace('"""', '\\"""') + '"""'
[ "def", "print_block_string", "(", "value", ":", "str", ",", "indentation", ":", "str", "=", "\"\"", ",", "prefer_multiple_lines", ":", "bool", "=", "False", ")", "->", "str", ":", "is_single_line", "=", "\"\\n\"", "not", "in", "value", "has_leading_space", "...
Print a block string in the indented block form. Prints a block string in the indented block form by adding a leading and trailing blank line. However, if a block string starts with whitespace and is a single-line, adding a leading blank line would strip that whitespace.
[ "Print", "a", "block", "string", "in", "the", "indented", "block", "form", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/block_string.py#L42-L67
226,121
graphql-python/graphql-core-next
graphql/utilities/type_comparators.py
is_equal_type
def is_equal_type(type_a: GraphQLType, type_b: GraphQLType): """Check whether two types are equal. Provided two types, return true if the types are equal (invariant).""" # Equivalent types are equal. if type_a is type_b: return True # If either type is non-null, the other must also be non-null. if is_non_null_type(type_a) and is_non_null_type(type_b): # noinspection PyUnresolvedReferences return is_equal_type(type_a.of_type, type_b.of_type) # type:ignore # If either type is a list, the other must also be a list. if is_list_type(type_a) and is_list_type(type_b): # noinspection PyUnresolvedReferences return is_equal_type(type_a.of_type, type_b.of_type) # type:ignore # Otherwise the types are not equal. return False
python
def is_equal_type(type_a: GraphQLType, type_b: GraphQLType): # Equivalent types are equal. if type_a is type_b: return True # If either type is non-null, the other must also be non-null. if is_non_null_type(type_a) and is_non_null_type(type_b): # noinspection PyUnresolvedReferences return is_equal_type(type_a.of_type, type_b.of_type) # type:ignore # If either type is a list, the other must also be a list. if is_list_type(type_a) and is_list_type(type_b): # noinspection PyUnresolvedReferences return is_equal_type(type_a.of_type, type_b.of_type) # type:ignore # Otherwise the types are not equal. return False
[ "def", "is_equal_type", "(", "type_a", ":", "GraphQLType", ",", "type_b", ":", "GraphQLType", ")", ":", "# Equivalent types are equal.", "if", "type_a", "is", "type_b", ":", "return", "True", "# If either type is non-null, the other must also be non-null.", "if", "is_non_...
Check whether two types are equal. Provided two types, return true if the types are equal (invariant).
[ "Check", "whether", "two", "types", "are", "equal", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/type_comparators.py#L19-L38
226,122
graphql-python/graphql-core-next
graphql/utilities/type_comparators.py
is_type_sub_type_of
def is_type_sub_type_of( schema: GraphQLSchema, maybe_subtype: GraphQLType, super_type: GraphQLType ) -> bool: """Check whether a type is subtype of another type in a given schema. Provided a type and a super type, return true if the first type is either equal or a subset of the second super type (covariant). """ # Equivalent type is a valid subtype if maybe_subtype is super_type: return True # If super_type is non-null, maybe_subtype must also be non-null. if is_non_null_type(super_type): if is_non_null_type(maybe_subtype): return is_type_sub_type_of( schema, cast(GraphQLNonNull, maybe_subtype).of_type, cast(GraphQLNonNull, super_type).of_type, ) return False elif is_non_null_type(maybe_subtype): # If super_type is nullable, maybe_subtype may be non-null or nullable. return is_type_sub_type_of( schema, cast(GraphQLNonNull, maybe_subtype).of_type, super_type ) # If superType type is a list, maybeSubType type must also be a list. if is_list_type(super_type): if is_list_type(maybe_subtype): return is_type_sub_type_of( schema, cast(GraphQLList, maybe_subtype).of_type, cast(GraphQLList, super_type).of_type, ) return False elif is_list_type(maybe_subtype): # If super_type is not a list, maybe_subtype must also be not a list. return False # If super_type type is an abstract type, maybe_subtype type may be a currently # possible object type. # noinspection PyTypeChecker if ( is_abstract_type(super_type) and is_object_type(maybe_subtype) and schema.is_possible_type( cast(GraphQLAbstractType, super_type), cast(GraphQLObjectType, maybe_subtype), ) ): return True # Otherwise, the child type is not a valid subtype of the parent type. return False
python
def is_type_sub_type_of( schema: GraphQLSchema, maybe_subtype: GraphQLType, super_type: GraphQLType ) -> bool: # Equivalent type is a valid subtype if maybe_subtype is super_type: return True # If super_type is non-null, maybe_subtype must also be non-null. if is_non_null_type(super_type): if is_non_null_type(maybe_subtype): return is_type_sub_type_of( schema, cast(GraphQLNonNull, maybe_subtype).of_type, cast(GraphQLNonNull, super_type).of_type, ) return False elif is_non_null_type(maybe_subtype): # If super_type is nullable, maybe_subtype may be non-null or nullable. return is_type_sub_type_of( schema, cast(GraphQLNonNull, maybe_subtype).of_type, super_type ) # If superType type is a list, maybeSubType type must also be a list. if is_list_type(super_type): if is_list_type(maybe_subtype): return is_type_sub_type_of( schema, cast(GraphQLList, maybe_subtype).of_type, cast(GraphQLList, super_type).of_type, ) return False elif is_list_type(maybe_subtype): # If super_type is not a list, maybe_subtype must also be not a list. return False # If super_type type is an abstract type, maybe_subtype type may be a currently # possible object type. # noinspection PyTypeChecker if ( is_abstract_type(super_type) and is_object_type(maybe_subtype) and schema.is_possible_type( cast(GraphQLAbstractType, super_type), cast(GraphQLObjectType, maybe_subtype), ) ): return True # Otherwise, the child type is not a valid subtype of the parent type. return False
[ "def", "is_type_sub_type_of", "(", "schema", ":", "GraphQLSchema", ",", "maybe_subtype", ":", "GraphQLType", ",", "super_type", ":", "GraphQLType", ")", "->", "bool", ":", "# Equivalent type is a valid subtype", "if", "maybe_subtype", "is", "super_type", ":", "return"...
Check whether a type is subtype of another type in a given schema. Provided a type and a super type, return true if the first type is either equal or a subset of the second super type (covariant).
[ "Check", "whether", "a", "type", "is", "subtype", "of", "another", "type", "in", "a", "given", "schema", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/type_comparators.py#L42-L96
226,123
graphql-python/graphql-core-next
graphql/utilities/type_comparators.py
do_types_overlap
def do_types_overlap(schema, type_a, type_b): """Check whether two types overlap in a given schema. Provided two composite types, determine if they "overlap". Two composite types overlap when the Sets of possible concrete types for each intersect. This is often used to determine if a fragment of a given type could possibly be visited in a context of another type. This function is commutative. """ # Equivalent types overlap if type_a is type_b: return True if is_abstract_type(type_a): if is_abstract_type(type_b): # If both types are abstract, then determine if there is any intersection # between possible concrete types of each. return any( schema.is_possible_type(type_b, type_) for type_ in schema.get_possible_types(type_a) ) # Determine if latter type is a possible concrete type of the former. return schema.is_possible_type(type_a, type_b) if is_abstract_type(type_b): # Determine if former type is a possible concrete type of the latter. return schema.is_possible_type(type_b, type_a) # Otherwise the types do not overlap. return False
python
def do_types_overlap(schema, type_a, type_b): # Equivalent types overlap if type_a is type_b: return True if is_abstract_type(type_a): if is_abstract_type(type_b): # If both types are abstract, then determine if there is any intersection # between possible concrete types of each. return any( schema.is_possible_type(type_b, type_) for type_ in schema.get_possible_types(type_a) ) # Determine if latter type is a possible concrete type of the former. return schema.is_possible_type(type_a, type_b) if is_abstract_type(type_b): # Determine if former type is a possible concrete type of the latter. return schema.is_possible_type(type_b, type_a) # Otherwise the types do not overlap. return False
[ "def", "do_types_overlap", "(", "schema", ",", "type_a", ",", "type_b", ")", ":", "# Equivalent types overlap", "if", "type_a", "is", "type_b", ":", "return", "True", "if", "is_abstract_type", "(", "type_a", ")", ":", "if", "is_abstract_type", "(", "type_b", "...
Check whether two types overlap in a given schema. Provided two composite types, determine if they "overlap". Two composite types overlap when the Sets of possible concrete types for each intersect. This is often used to determine if a fragment of a given type could possibly be visited in a context of another type. This function is commutative.
[ "Check", "whether", "two", "types", "overlap", "in", "a", "given", "schema", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/type_comparators.py#L99-L130
226,124
graphql-python/graphql-core-next
graphql/utilities/concat_ast.py
concat_ast
def concat_ast(asts: Sequence[DocumentNode]) -> DocumentNode: """Concat ASTs. Provided a collection of ASTs, presumably each from different files, concatenate the ASTs together into batched AST, useful for validating many GraphQL source files which together represent one conceptual application. """ return DocumentNode( definitions=list(chain.from_iterable(document.definitions for document in asts)) )
python
def concat_ast(asts: Sequence[DocumentNode]) -> DocumentNode: return DocumentNode( definitions=list(chain.from_iterable(document.definitions for document in asts)) )
[ "def", "concat_ast", "(", "asts", ":", "Sequence", "[", "DocumentNode", "]", ")", "->", "DocumentNode", ":", "return", "DocumentNode", "(", "definitions", "=", "list", "(", "chain", ".", "from_iterable", "(", "document", ".", "definitions", "for", "document", ...
Concat ASTs. Provided a collection of ASTs, presumably each from different files, concatenate the ASTs together into batched AST, useful for validating many GraphQL source files which together represent one conceptual application.
[ "Concat", "ASTs", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/concat_ast.py#L9-L18
226,125
graphql-python/graphql-core-next
graphql/pyutils/suggestion_list.py
suggestion_list
def suggestion_list(input_: str, options: Collection[str]): """Get list with suggestions for a given input. Given an invalid input string and list of valid options, returns a filtered list of valid options sorted based on their similarity with the input. """ options_by_distance = {} input_threshold = len(input_) // 2 for option in options: distance = lexical_distance(input_, option) threshold = max(input_threshold, len(option) // 2, 1) if distance <= threshold: options_by_distance[option] = distance return sorted(options_by_distance, key=options_by_distance.get)
python
def suggestion_list(input_: str, options: Collection[str]): options_by_distance = {} input_threshold = len(input_) // 2 for option in options: distance = lexical_distance(input_, option) threshold = max(input_threshold, len(option) // 2, 1) if distance <= threshold: options_by_distance[option] = distance return sorted(options_by_distance, key=options_by_distance.get)
[ "def", "suggestion_list", "(", "input_", ":", "str", ",", "options", ":", "Collection", "[", "str", "]", ")", ":", "options_by_distance", "=", "{", "}", "input_threshold", "=", "len", "(", "input_", ")", "//", "2", "for", "option", "in", "options", ":", ...
Get list with suggestions for a given input. Given an invalid input string and list of valid options, returns a filtered list of valid options sorted based on their similarity with the input.
[ "Get", "list", "with", "suggestions", "for", "a", "given", "input", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/suggestion_list.py#L6-L21
226,126
graphql-python/graphql-core-next
graphql/pyutils/suggestion_list.py
lexical_distance
def lexical_distance(a_str: str, b_str: str) -> int: """Computes the lexical distance between strings A and B. The "distance" between two strings is given by counting the minimum number of edits needed to transform string A into string B. An edit can be an insertion, deletion, or substitution of a single character, or a swap of two adjacent characters. This distance can be useful for detecting typos in input or sorting. """ if a_str == b_str: return 0 a, b = a_str.lower(), b_str.lower() a_len, b_len = len(a), len(b) # Any case change counts as a single edit if a == b: return 1 d = [[j for j in range(0, b_len + 1)]] for i in range(1, a_len + 1): d.append([i] + [0] * b_len) for i in range(1, a_len + 1): for j in range(1, b_len + 1): cost = 0 if a[i - 1] == b[j - 1] else 1 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost) if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]: d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost) return d[a_len][b_len]
python
def lexical_distance(a_str: str, b_str: str) -> int: if a_str == b_str: return 0 a, b = a_str.lower(), b_str.lower() a_len, b_len = len(a), len(b) # Any case change counts as a single edit if a == b: return 1 d = [[j for j in range(0, b_len + 1)]] for i in range(1, a_len + 1): d.append([i] + [0] * b_len) for i in range(1, a_len + 1): for j in range(1, b_len + 1): cost = 0 if a[i - 1] == b[j - 1] else 1 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost) if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]: d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost) return d[a_len][b_len]
[ "def", "lexical_distance", "(", "a_str", ":", "str", ",", "b_str", ":", "str", ")", "->", "int", ":", "if", "a_str", "==", "b_str", ":", "return", "0", "a", ",", "b", "=", "a_str", ".", "lower", "(", ")", ",", "b_str", ".", "lower", "(", ")", "...
Computes the lexical distance between strings A and B. The "distance" between two strings is given by counting the minimum number of edits needed to transform string A into string B. An edit can be an insertion, deletion, or substitution of a single character, or a swap of two adjacent characters. This distance can be useful for detecting typos in input or sorting.
[ "Computes", "the", "lexical", "distance", "between", "strings", "A", "and", "B", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/suggestion_list.py#L24-L56
226,127
graphql-python/graphql-core-next
graphql/utilities/get_operation_ast.py
get_operation_ast
def get_operation_ast( document_ast: DocumentNode, operation_name: Optional[str] = None ) -> Optional[OperationDefinitionNode]: """Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document. """ operation = None for definition in document_ast.definitions: if isinstance(definition, OperationDefinitionNode): if not operation_name: # If no operation name was provided, only return an Operation if there # is one defined in the document. # Upon encountering the second, return None. if operation: return None operation = definition elif definition.name and definition.name.value == operation_name: return definition return operation
python
def get_operation_ast( document_ast: DocumentNode, operation_name: Optional[str] = None ) -> Optional[OperationDefinitionNode]: operation = None for definition in document_ast.definitions: if isinstance(definition, OperationDefinitionNode): if not operation_name: # If no operation name was provided, only return an Operation if there # is one defined in the document. # Upon encountering the second, return None. if operation: return None operation = definition elif definition.name and definition.name.value == operation_name: return definition return operation
[ "def", "get_operation_ast", "(", "document_ast", ":", "DocumentNode", ",", "operation_name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Optional", "[", "OperationDefinitionNode", "]", ":", "operation", "=", "None", "for", "definition", "in", "d...
Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document.
[ "Get", "operation", "AST", "node", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/get_operation_ast.py#L8-L29
226,128
graphql-python/graphql-core-next
graphql/error/format_error.py
format_error
def format_error(error: "GraphQLError") -> dict: """Format a GraphQL error Given a GraphQLError, format it according to the rules described by the "Response Format, Errors" section of the GraphQL Specification. """ if not error: raise ValueError("Received null or undefined error.") formatted: Dict[str, Any] = dict( # noqa: E701 (pycqa/flake8#394) message=error.message or "An unknown error occurred.", locations=error.locations, path=error.path, ) if error.extensions: formatted.update(extensions=error.extensions) return formatted
python
def format_error(error: "GraphQLError") -> dict: if not error: raise ValueError("Received null or undefined error.") formatted: Dict[str, Any] = dict( # noqa: E701 (pycqa/flake8#394) message=error.message or "An unknown error occurred.", locations=error.locations, path=error.path, ) if error.extensions: formatted.update(extensions=error.extensions) return formatted
[ "def", "format_error", "(", "error", ":", "\"GraphQLError\"", ")", "->", "dict", ":", "if", "not", "error", ":", "raise", "ValueError", "(", "\"Received null or undefined error.\"", ")", "formatted", ":", "Dict", "[", "str", ",", "Any", "]", "=", "dict", "("...
Format a GraphQL error Given a GraphQLError, format it according to the rules described by the "Response Format, Errors" section of the GraphQL Specification.
[ "Format", "a", "GraphQL", "error" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/error/format_error.py#L10-L25
226,129
graphql-python/graphql-core-next
graphql/graphql.py
graphql
async def graphql( schema: GraphQLSchema, source: Union[str, Source], root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, type_resolver: GraphQLTypeResolver = None, middleware: Middleware = None, execution_context_class: Type[ExecutionContext] = ExecutionContext, ) -> ExecutionResult: """Execute a GraphQL operation asynchronously. This is the primary entry point function for fulfilling GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema. More sophisticated GraphQL servers, such as those which persist queries, may wish to separate the validation and execution phases to a static time tooling step, and a server runtime step. Accepts the following arguments: :arg schema: The GraphQL type system to use when validating and executing a query. :arg source: A GraphQL language formatted string representing the requested operation. :arg root_value: The value provided as the first argument to resolver functions on the top level type (e.g. the query object type). :arg context_value: The context value is provided as an attribute of the second argument (the resolve info) to resolver functions. It is used to pass shared information useful at any point during query execution, for example the currently logged in user and connections to databases or other services. :arg variable_values: A mapping of variable name to runtime value to use for all variables defined in the request string. :arg operation_name: The name of the operation to use if request string contains multiple possible operations. Can be omitted if request string contains only one operation. :arg field_resolver: A resolver function to use when one is not provided by the schema. If not provided, the default field resolver is used (which looks for a value or method on the source value with the field's name). :arg type_resolver: A type resolver function to use when none is provided by the schema. If not provided, the default type resolver is used (which looks for a `__typename` field or alternatively calls the `isTypeOf` method). :arg middleware: The middleware to wrap the resolvers with :arg execution_context_class: The execution context class to use to build the context """ # Always return asynchronously for a consistent API. result = graphql_impl( schema, source, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, execution_context_class, ) if isawaitable(result): return await cast(Awaitable[ExecutionResult], result) return cast(ExecutionResult, result)
python
async def graphql( schema: GraphQLSchema, source: Union[str, Source], root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, type_resolver: GraphQLTypeResolver = None, middleware: Middleware = None, execution_context_class: Type[ExecutionContext] = ExecutionContext, ) -> ExecutionResult: # Always return asynchronously for a consistent API. result = graphql_impl( schema, source, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, execution_context_class, ) if isawaitable(result): return await cast(Awaitable[ExecutionResult], result) return cast(ExecutionResult, result)
[ "async", "def", "graphql", "(", "schema", ":", "GraphQLSchema", ",", "source", ":", "Union", "[", "str", ",", "Source", "]", ",", "root_value", ":", "Any", "=", "None", ",", "context_value", ":", "Any", "=", "None", ",", "variable_values", ":", "Dict", ...
Execute a GraphQL operation asynchronously. This is the primary entry point function for fulfilling GraphQL operations by parsing, validating, and executing a GraphQL document along side a GraphQL schema. More sophisticated GraphQL servers, such as those which persist queries, may wish to separate the validation and execution phases to a static time tooling step, and a server runtime step. Accepts the following arguments: :arg schema: The GraphQL type system to use when validating and executing a query. :arg source: A GraphQL language formatted string representing the requested operation. :arg root_value: The value provided as the first argument to resolver functions on the top level type (e.g. the query object type). :arg context_value: The context value is provided as an attribute of the second argument (the resolve info) to resolver functions. It is used to pass shared information useful at any point during query execution, for example the currently logged in user and connections to databases or other services. :arg variable_values: A mapping of variable name to runtime value to use for all variables defined in the request string. :arg operation_name: The name of the operation to use if request string contains multiple possible operations. Can be omitted if request string contains only one operation. :arg field_resolver: A resolver function to use when one is not provided by the schema. If not provided, the default field resolver is used (which looks for a value or method on the source value with the field's name). :arg type_resolver: A type resolver function to use when none is provided by the schema. If not provided, the default type resolver is used (which looks for a `__typename` field or alternatively calls the `isTypeOf` method). :arg middleware: The middleware to wrap the resolvers with :arg execution_context_class: The execution context class to use to build the context
[ "Execute", "a", "GraphQL", "operation", "asynchronously", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/graphql.py#L19-L90
226,130
graphql-python/graphql-core-next
graphql/graphql.py
graphql_impl
def graphql_impl( schema, source, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, execution_context_class, ) -> AwaitableOrValue[ExecutionResult]: """Execute a query, return asynchronously only if necessary.""" # Validate Schema schema_validation_errors = validate_schema(schema) if schema_validation_errors: return ExecutionResult(data=None, errors=schema_validation_errors) # Parse try: document = parse(source) except GraphQLError as error: return ExecutionResult(data=None, errors=[error]) except Exception as error: error = GraphQLError(str(error), original_error=error) return ExecutionResult(data=None, errors=[error]) # Validate from .validation import validate validation_errors = validate(schema, document) if validation_errors: return ExecutionResult(data=None, errors=validation_errors) # Execute return execute( schema, document, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, execution_context_class, )
python
def graphql_impl( schema, source, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, execution_context_class, ) -> AwaitableOrValue[ExecutionResult]: # Validate Schema schema_validation_errors = validate_schema(schema) if schema_validation_errors: return ExecutionResult(data=None, errors=schema_validation_errors) # Parse try: document = parse(source) except GraphQLError as error: return ExecutionResult(data=None, errors=[error]) except Exception as error: error = GraphQLError(str(error), original_error=error) return ExecutionResult(data=None, errors=[error]) # Validate from .validation import validate validation_errors = validate(schema, document) if validation_errors: return ExecutionResult(data=None, errors=validation_errors) # Execute return execute( schema, document, root_value, context_value, variable_values, operation_name, field_resolver, type_resolver, middleware, execution_context_class, )
[ "def", "graphql_impl", "(", "schema", ",", "source", ",", "root_value", ",", "context_value", ",", "variable_values", ",", "operation_name", ",", "field_resolver", ",", "type_resolver", ",", "middleware", ",", "execution_context_class", ",", ")", "->", "AwaitableOrV...
Execute a query, return asynchronously only if necessary.
[ "Execute", "a", "query", "return", "asynchronously", "only", "if", "necessary", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/graphql.py#L133-L179
226,131
graphql-python/graphql-core-next
graphql/type/definition.py
get_named_type
def get_named_type(type_): # noqa: F811 """Unwrap possible wrapping type""" if type_: unwrapped_type = type_ while is_wrapping_type(unwrapped_type): unwrapped_type = cast(GraphQLWrappingType, unwrapped_type) unwrapped_type = unwrapped_type.of_type return cast(GraphQLNamedType, unwrapped_type) return None
python
def get_named_type(type_): # noqa: F811 if type_: unwrapped_type = type_ while is_wrapping_type(unwrapped_type): unwrapped_type = cast(GraphQLWrappingType, unwrapped_type) unwrapped_type = unwrapped_type.of_type return cast(GraphQLNamedType, unwrapped_type) return None
[ "def", "get_named_type", "(", "type_", ")", ":", "# noqa: F811", "if", "type_", ":", "unwrapped_type", "=", "type_", "while", "is_wrapping_type", "(", "unwrapped_type", ")", ":", "unwrapped_type", "=", "cast", "(", "GraphQLWrappingType", ",", "unwrapped_type", ")"...
Unwrap possible wrapping type
[ "Unwrap", "possible", "wrapping", "type" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/definition.py#L261-L269
226,132
graphql-python/graphql-core-next
graphql/type/definition.py
get_nullable_type
def get_nullable_type(type_): # noqa: F811 """Unwrap possible non-null type""" if is_non_null_type(type_): type_ = cast(GraphQLNonNull, type_) type_ = type_.of_type return cast(Optional[GraphQLNullableType], type_)
python
def get_nullable_type(type_): # noqa: F811 if is_non_null_type(type_): type_ = cast(GraphQLNonNull, type_) type_ = type_.of_type return cast(Optional[GraphQLNullableType], type_)
[ "def", "get_nullable_type", "(", "type_", ")", ":", "# noqa: F811", "if", "is_non_null_type", "(", "type_", ")", ":", "type_", "=", "cast", "(", "GraphQLNonNull", ",", "type_", ")", "type_", "=", "type_", ".", "of_type", "return", "cast", "(", "Optional", ...
Unwrap possible non-null type
[ "Unwrap", "possible", "non", "-", "null", "type" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/definition.py#L1365-L1370
226,133
graphql-python/graphql-core-next
graphql/type/definition.py
GraphQLObjectType.fields
def fields(self) -> GraphQLFieldMap: """Get provided fields, wrapping them as GraphQLFields if needed.""" try: fields = resolve_thunk(self._fields) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} fields cannot be resolved: {error}") if not isinstance(fields, dict) or not all( isinstance(key, str) for key in fields ): raise TypeError( f"{self.name} fields must be a dict with field names as keys" " or a function which returns such an object." ) if not all( isinstance(value, GraphQLField) or is_output_type(value) for value in fields.values() ): raise TypeError( f"{self.name} fields must be GraphQLField or output type objects." ) return { name: value if isinstance(value, GraphQLField) else GraphQLField(value) for name, value in fields.items() }
python
def fields(self) -> GraphQLFieldMap: try: fields = resolve_thunk(self._fields) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} fields cannot be resolved: {error}") if not isinstance(fields, dict) or not all( isinstance(key, str) for key in fields ): raise TypeError( f"{self.name} fields must be a dict with field names as keys" " or a function which returns such an object." ) if not all( isinstance(value, GraphQLField) or is_output_type(value) for value in fields.values() ): raise TypeError( f"{self.name} fields must be GraphQLField or output type objects." ) return { name: value if isinstance(value, GraphQLField) else GraphQLField(value) for name, value in fields.items() }
[ "def", "fields", "(", "self", ")", "->", "GraphQLFieldMap", ":", "try", ":", "fields", "=", "resolve_thunk", "(", "self", ".", "_fields", ")", "except", "GraphQLError", ":", "raise", "except", "Exception", "as", "error", ":", "raise", "TypeError", "(", "f\...
Get provided fields, wrapping them as GraphQLFields if needed.
[ "Get", "provided", "fields", "wrapping", "them", "as", "GraphQLFields", "if", "needed", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/definition.py#L652-L677
226,134
graphql-python/graphql-core-next
graphql/type/definition.py
GraphQLObjectType.interfaces
def interfaces(self) -> GraphQLInterfaceList: """Get provided interfaces.""" try: interfaces = resolve_thunk(self._interfaces) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} interfaces cannot be resolved: {error}") if interfaces is None: interfaces = [] if not isinstance(interfaces, (list, tuple)): raise TypeError( f"{self.name} interfaces must be a list/tuple" " or a function which returns a list/tuple." ) if not all(isinstance(value, GraphQLInterfaceType) for value in interfaces): raise TypeError(f"{self.name} interfaces must be GraphQLInterface objects.") return interfaces[:]
python
def interfaces(self) -> GraphQLInterfaceList: try: interfaces = resolve_thunk(self._interfaces) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} interfaces cannot be resolved: {error}") if interfaces is None: interfaces = [] if not isinstance(interfaces, (list, tuple)): raise TypeError( f"{self.name} interfaces must be a list/tuple" " or a function which returns a list/tuple." ) if not all(isinstance(value, GraphQLInterfaceType) for value in interfaces): raise TypeError(f"{self.name} interfaces must be GraphQLInterface objects.") return interfaces[:]
[ "def", "interfaces", "(", "self", ")", "->", "GraphQLInterfaceList", ":", "try", ":", "interfaces", "=", "resolve_thunk", "(", "self", ".", "_interfaces", ")", "except", "GraphQLError", ":", "raise", "except", "Exception", "as", "error", ":", "raise", "TypeErr...
Get provided interfaces.
[ "Get", "provided", "interfaces", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/definition.py#L680-L697
226,135
graphql-python/graphql-core-next
graphql/type/definition.py
GraphQLUnionType.types
def types(self) -> GraphQLTypeList: """Get provided types.""" try: types = resolve_thunk(self._types) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} types cannot be resolved: {error}") if types is None: types = [] if not isinstance(types, (list, tuple)): raise TypeError( f"{self.name} types must be a list/tuple" " or a function which returns a list/tuple." ) if not all(isinstance(value, GraphQLObjectType) for value in types): raise TypeError(f"{self.name} types must be GraphQLObjectType objects.") return types[:]
python
def types(self) -> GraphQLTypeList: try: types = resolve_thunk(self._types) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} types cannot be resolved: {error}") if types is None: types = [] if not isinstance(types, (list, tuple)): raise TypeError( f"{self.name} types must be a list/tuple" " or a function which returns a list/tuple." ) if not all(isinstance(value, GraphQLObjectType) for value in types): raise TypeError(f"{self.name} types must be GraphQLObjectType objects.") return types[:]
[ "def", "types", "(", "self", ")", "->", "GraphQLTypeList", ":", "try", ":", "types", "=", "resolve_thunk", "(", "self", ".", "_types", ")", "except", "GraphQLError", ":", "raise", "except", "Exception", "as", "error", ":", "raise", "TypeError", "(", "f\"{s...
Get provided types.
[ "Get", "provided", "types", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/definition.py#L871-L888
226,136
graphql-python/graphql-core-next
graphql/type/definition.py
GraphQLInputObjectType.fields
def fields(self) -> GraphQLInputFieldMap: """Get provided fields, wrap them as GraphQLInputField if needed.""" try: fields = resolve_thunk(self._fields) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} fields cannot be resolved: {error}") if not isinstance(fields, dict) or not all( isinstance(key, str) for key in fields ): raise TypeError( f"{self.name} fields must be a dict with field names as keys" " or a function which returns such an object." ) if not all( isinstance(value, GraphQLInputField) or is_input_type(value) for value in fields.values() ): raise TypeError( f"{self.name} fields must be" " GraphQLInputField or input type objects." ) return { name: value if isinstance(value, GraphQLInputField) else GraphQLInputField(value) for name, value in fields.items() }
python
def fields(self) -> GraphQLInputFieldMap: try: fields = resolve_thunk(self._fields) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} fields cannot be resolved: {error}") if not isinstance(fields, dict) or not all( isinstance(key, str) for key in fields ): raise TypeError( f"{self.name} fields must be a dict with field names as keys" " or a function which returns such an object." ) if not all( isinstance(value, GraphQLInputField) or is_input_type(value) for value in fields.values() ): raise TypeError( f"{self.name} fields must be" " GraphQLInputField or input type objects." ) return { name: value if isinstance(value, GraphQLInputField) else GraphQLInputField(value) for name, value in fields.items() }
[ "def", "fields", "(", "self", ")", "->", "GraphQLInputFieldMap", ":", "try", ":", "fields", "=", "resolve_thunk", "(", "self", ".", "_fields", ")", "except", "GraphQLError", ":", "raise", "except", "Exception", "as", "error", ":", "raise", "TypeError", "(", ...
Get provided fields, wrap them as GraphQLInputField if needed.
[ "Get", "provided", "fields", "wrap", "them", "as", "GraphQLInputField", "if", "needed", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/definition.py#L1148-L1176
226,137
graphql-python/graphql-core-next
graphql/error/located_error.py
located_error
def located_error( original_error: Union[Exception, GraphQLError], nodes: Sequence["Node"], path: Sequence[Union[str, int]], ) -> GraphQLError: """Located GraphQL Error Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL operation, produce a new GraphQLError aware of the location in the document responsible for the original Error. """ if original_error: # Note: this uses a brand-check to support GraphQL errors originating from # other contexts. try: if isinstance(original_error.path, list): # type: ignore return original_error # type: ignore except AttributeError: pass try: message = original_error.message # type: ignore except AttributeError: message = str(original_error) try: source = original_error.source # type: ignore except AttributeError: source = None try: positions = original_error.positions # type: ignore except AttributeError: positions = None try: nodes = original_error.nodes or nodes # type: ignore except AttributeError: pass return GraphQLError(message, nodes, source, positions, path, original_error)
python
def located_error( original_error: Union[Exception, GraphQLError], nodes: Sequence["Node"], path: Sequence[Union[str, int]], ) -> GraphQLError: if original_error: # Note: this uses a brand-check to support GraphQL errors originating from # other contexts. try: if isinstance(original_error.path, list): # type: ignore return original_error # type: ignore except AttributeError: pass try: message = original_error.message # type: ignore except AttributeError: message = str(original_error) try: source = original_error.source # type: ignore except AttributeError: source = None try: positions = original_error.positions # type: ignore except AttributeError: positions = None try: nodes = original_error.nodes or nodes # type: ignore except AttributeError: pass return GraphQLError(message, nodes, source, positions, path, original_error)
[ "def", "located_error", "(", "original_error", ":", "Union", "[", "Exception", ",", "GraphQLError", "]", ",", "nodes", ":", "Sequence", "[", "\"Node\"", "]", ",", "path", ":", "Sequence", "[", "Union", "[", "str", ",", "int", "]", "]", ",", ")", "->", ...
Located GraphQL Error Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL operation, produce a new GraphQLError aware of the location in the document responsible for the original Error.
[ "Located", "GraphQL", "Error" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/error/located_error.py#L11-L46
226,138
graphql-python/graphql-core-next
graphql/utilities/assert_valid_name.py
assert_valid_name
def assert_valid_name(name: str) -> str: """Uphold the spec rules about naming.""" error = is_valid_name_error(name) if error: raise error return name
python
def assert_valid_name(name: str) -> str: error = is_valid_name_error(name) if error: raise error return name
[ "def", "assert_valid_name", "(", "name", ":", "str", ")", "->", "str", ":", "error", "=", "is_valid_name_error", "(", "name", ")", "if", "error", ":", "raise", "error", "return", "name" ]
Uphold the spec rules about naming.
[ "Uphold", "the", "spec", "rules", "about", "naming", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/assert_valid_name.py#L13-L18
226,139
graphql-python/graphql-core-next
graphql/utilities/assert_valid_name.py
is_valid_name_error
def is_valid_name_error(name: str, node: Node = None) -> Optional[GraphQLError]: """Return an Error if a name is invalid.""" if not isinstance(name, str): raise TypeError("Expected string") if name.startswith("__"): return GraphQLError( f"Name {name!r} must not begin with '__'," " which is reserved by GraphQL introspection.", node, ) if not re_name.match(name): return GraphQLError( f"Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but {name!r} does not.", node ) return None
python
def is_valid_name_error(name: str, node: Node = None) -> Optional[GraphQLError]: if not isinstance(name, str): raise TypeError("Expected string") if name.startswith("__"): return GraphQLError( f"Name {name!r} must not begin with '__'," " which is reserved by GraphQL introspection.", node, ) if not re_name.match(name): return GraphQLError( f"Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but {name!r} does not.", node ) return None
[ "def", "is_valid_name_error", "(", "name", ":", "str", ",", "node", ":", "Node", "=", "None", ")", "->", "Optional", "[", "GraphQLError", "]", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Expected strin...
Return an Error if a name is invalid.
[ "Return", "an", "Error", "if", "a", "name", "is", "invalid", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/assert_valid_name.py#L21-L35
226,140
graphql-python/graphql-core-next
graphql/subscription/subscribe.py
subscribe
async def subscribe( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, subscribe_field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterator[ExecutionResult], ExecutionResult]: """Create a GraphQL subscription. Implements the "Subscribe" algorithm described in the GraphQL spec. Returns a coroutine object which yields either an AsyncIterator (if successful) or an ExecutionResult (client error). The coroutine will raise an exception if a server error occurs. If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned. If the source stream could not be created due to faulty subscription resolver logic or underlying systems, the coroutine object will yield a single ExecutionResult containing `errors` and no `data`. If the operation succeeded, the coroutine will yield an AsyncIterator, which yields a stream of ExecutionResults representing the response stream. """ try: result_or_stream = await create_source_event_stream( schema, document, root_value, context_value, variable_values, operation_name, subscribe_field_resolver, ) except GraphQLError as error: return ExecutionResult(data=None, errors=[error]) if isinstance(result_or_stream, ExecutionResult): return result_or_stream result_or_stream = cast(AsyncIterable, result_or_stream) async def map_source_to_response(payload): """Map source to response. For each payload yielded from a subscription, map it over the normal GraphQL `execute` function, with `payload` as the `root_value`. This implements the "MapSourceToResponseEvent" algorithm described in the GraphQL specification. The `execute` function provides the "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the "ExecuteQuery" algorithm, for which `execute` is also used. """ result = execute( schema, document, payload, context_value, variable_values, operation_name, field_resolver, ) return await result if isawaitable(result) else result return MapAsyncIterator(result_or_stream, map_source_to_response)
python
async def subscribe( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, subscribe_field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterator[ExecutionResult], ExecutionResult]: try: result_or_stream = await create_source_event_stream( schema, document, root_value, context_value, variable_values, operation_name, subscribe_field_resolver, ) except GraphQLError as error: return ExecutionResult(data=None, errors=[error]) if isinstance(result_or_stream, ExecutionResult): return result_or_stream result_or_stream = cast(AsyncIterable, result_or_stream) async def map_source_to_response(payload): """Map source to response. For each payload yielded from a subscription, map it over the normal GraphQL `execute` function, with `payload` as the `root_value`. This implements the "MapSourceToResponseEvent" algorithm described in the GraphQL specification. The `execute` function provides the "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the "ExecuteQuery" algorithm, for which `execute` is also used. """ result = execute( schema, document, payload, context_value, variable_values, operation_name, field_resolver, ) return await result if isawaitable(result) else result return MapAsyncIterator(result_or_stream, map_source_to_response)
[ "async", "def", "subscribe", "(", "schema", ":", "GraphQLSchema", ",", "document", ":", "DocumentNode", ",", "root_value", ":", "Any", "=", "None", ",", "context_value", ":", "Any", "=", "None", ",", "variable_values", ":", "Dict", "[", "str", ",", "Any", ...
Create a GraphQL subscription. Implements the "Subscribe" algorithm described in the GraphQL spec. Returns a coroutine object which yields either an AsyncIterator (if successful) or an ExecutionResult (client error). The coroutine will raise an exception if a server error occurs. If the client-provided arguments to this function do not result in a compliant subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no data will be returned. If the source stream could not be created due to faulty subscription resolver logic or underlying systems, the coroutine object will yield a single ExecutionResult containing `errors` and no `data`. If the operation succeeded, the coroutine will yield an AsyncIterator, which yields a stream of ExecutionResults representing the response stream.
[ "Create", "a", "GraphQL", "subscription", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/subscription/subscribe.py#L22-L88
226,141
graphql-python/graphql-core-next
graphql/subscription/subscribe.py
create_source_event_stream
async def create_source_event_stream( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterable[Any], ExecutionResult]: """Create source even stream Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream. Returns a coroutine that yields an AsyncIterable. If the client provided invalid arguments, the source stream could not be created, or the resolver did not return an AsyncIterable, this function will throw an error, which should be caught and handled by the caller. A Source Event Stream represents a sequence of events, each of which triggers a GraphQL execution for that event. This may be useful when hosting the stateful subscription service in a different process or machine than the stateless GraphQL execution engine, or otherwise separating these two steps. For more on this, see the "Supporting Subscriptions at Scale" information in the GraphQL spec. """ # If arguments are missing or incorrectly typed, this is an internal developer # mistake which should throw an early error. assert_valid_execution_arguments(schema, document, variable_values) # If a valid context cannot be created due to incorrect arguments, this will throw # an error. context = ExecutionContext.build( schema, document, root_value, context_value, variable_values, operation_name, field_resolver, ) # Return early errors if execution context failed. if isinstance(context, list): return ExecutionResult(data=None, errors=context) type_ = get_operation_root_type(schema, context.operation) fields = context.collect_fields(type_, context.operation.selection_set, {}, set()) response_names = list(fields) response_name = response_names[0] field_nodes = fields[response_name] field_node = field_nodes[0] field_name = field_node.name.value field_def = get_field_def(schema, type_, field_name) if not field_def: raise GraphQLError( f"The subscription field '{field_name}' is not defined.", field_nodes ) # Call the `subscribe()` resolver or the default resolver to produce an # AsyncIterable yielding raw payloads. resolve_fn = field_def.subscribe or context.field_resolver resolve_fn = cast(GraphQLFieldResolver, resolve_fn) # help mypy path = add_path(None, response_name) info = context.build_resolve_info(field_def, field_nodes, type_, path) # `resolve_field_value_or_error` implements the "ResolveFieldEventStream" algorithm # from GraphQL specification. It differs from `resolve_field_value` due to # providing a different `resolve_fn`. result = context.resolve_field_value_or_error( field_def, field_nodes, resolve_fn, root_value, info ) event_stream = await cast(Awaitable, result) if isawaitable(result) else result # If `event_stream` is an Error, rethrow a located error. if isinstance(event_stream, Exception): raise located_error(event_stream, field_nodes, response_path_as_list(path)) # Assert field returned an event stream, otherwise yield an error. if isinstance(event_stream, AsyncIterable): return cast(AsyncIterable, event_stream) raise TypeError( f"Subscription field must return AsyncIterable. Received: {event_stream!r}" )
python
async def create_source_event_stream( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterable[Any], ExecutionResult]: # If arguments are missing or incorrectly typed, this is an internal developer # mistake which should throw an early error. assert_valid_execution_arguments(schema, document, variable_values) # If a valid context cannot be created due to incorrect arguments, this will throw # an error. context = ExecutionContext.build( schema, document, root_value, context_value, variable_values, operation_name, field_resolver, ) # Return early errors if execution context failed. if isinstance(context, list): return ExecutionResult(data=None, errors=context) type_ = get_operation_root_type(schema, context.operation) fields = context.collect_fields(type_, context.operation.selection_set, {}, set()) response_names = list(fields) response_name = response_names[0] field_nodes = fields[response_name] field_node = field_nodes[0] field_name = field_node.name.value field_def = get_field_def(schema, type_, field_name) if not field_def: raise GraphQLError( f"The subscription field '{field_name}' is not defined.", field_nodes ) # Call the `subscribe()` resolver or the default resolver to produce an # AsyncIterable yielding raw payloads. resolve_fn = field_def.subscribe or context.field_resolver resolve_fn = cast(GraphQLFieldResolver, resolve_fn) # help mypy path = add_path(None, response_name) info = context.build_resolve_info(field_def, field_nodes, type_, path) # `resolve_field_value_or_error` implements the "ResolveFieldEventStream" algorithm # from GraphQL specification. It differs from `resolve_field_value` due to # providing a different `resolve_fn`. result = context.resolve_field_value_or_error( field_def, field_nodes, resolve_fn, root_value, info ) event_stream = await cast(Awaitable, result) if isawaitable(result) else result # If `event_stream` is an Error, rethrow a located error. if isinstance(event_stream, Exception): raise located_error(event_stream, field_nodes, response_path_as_list(path)) # Assert field returned an event stream, otherwise yield an error. if isinstance(event_stream, AsyncIterable): return cast(AsyncIterable, event_stream) raise TypeError( f"Subscription field must return AsyncIterable. Received: {event_stream!r}" )
[ "async", "def", "create_source_event_stream", "(", "schema", ":", "GraphQLSchema", ",", "document", ":", "DocumentNode", ",", "root_value", ":", "Any", "=", "None", ",", "context_value", ":", "Any", "=", "None", ",", "variable_values", ":", "Dict", "[", "str",...
Create source even stream Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream. Returns a coroutine that yields an AsyncIterable. If the client provided invalid arguments, the source stream could not be created, or the resolver did not return an AsyncIterable, this function will throw an error, which should be caught and handled by the caller. A Source Event Stream represents a sequence of events, each of which triggers a GraphQL execution for that event. This may be useful when hosting the stateful subscription service in a different process or machine than the stateless GraphQL execution engine, or otherwise separating these two steps. For more on this, see the "Supporting Subscriptions at Scale" information in the GraphQL spec.
[ "Create", "source", "even", "stream" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/subscription/subscribe.py#L91-L178
226,142
graphql-python/graphql-core-next
graphql/language/visitor.py
Visitor.get_visit_fn
def get_visit_fn(cls, kind, is_leaving=False) -> Callable: """Get the visit function for the given node kind and direction.""" method = "leave" if is_leaving else "enter" visit_fn = getattr(cls, f"{method}_{kind}", None) if not visit_fn: visit_fn = getattr(cls, method, None) return visit_fn
python
def get_visit_fn(cls, kind, is_leaving=False) -> Callable: method = "leave" if is_leaving else "enter" visit_fn = getattr(cls, f"{method}_{kind}", None) if not visit_fn: visit_fn = getattr(cls, method, None) return visit_fn
[ "def", "get_visit_fn", "(", "cls", ",", "kind", ",", "is_leaving", "=", "False", ")", "->", "Callable", ":", "method", "=", "\"leave\"", "if", "is_leaving", "else", "\"enter\"", "visit_fn", "=", "getattr", "(", "cls", ",", "f\"{method}_{kind}\"", ",", "None"...
Get the visit function for the given node kind and direction.
[ "Get", "the", "visit", "function", "for", "the", "given", "node", "kind", "and", "direction", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/visitor.py#L174-L180
226,143
graphql-python/graphql-core-next
graphql/type/validate.py
validate_schema
def validate_schema(schema: GraphQLSchema) -> List[GraphQLError]: """Validate a GraphQL schema. Implements the "Type Validation" sub-sections of the specification's "Type System" section. Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the Schema is valid. """ # First check to ensure the provided value is in fact a GraphQLSchema. assert_schema(schema) # If this Schema has already been validated, return the previous results. # noinspection PyProtectedMember errors = schema._validation_errors if errors is None: # Validate the schema, producing a list of errors. context = SchemaValidationContext(schema) context.validate_root_types() context.validate_directives() context.validate_types() # Persist the results of validation before returning to ensure validation does # not run multiple times for this schema. errors = context.errors schema._validation_errors = errors return errors
python
def validate_schema(schema: GraphQLSchema) -> List[GraphQLError]: # First check to ensure the provided value is in fact a GraphQLSchema. assert_schema(schema) # If this Schema has already been validated, return the previous results. # noinspection PyProtectedMember errors = schema._validation_errors if errors is None: # Validate the schema, producing a list of errors. context = SchemaValidationContext(schema) context.validate_root_types() context.validate_directives() context.validate_types() # Persist the results of validation before returning to ensure validation does # not run multiple times for this schema. errors = context.errors schema._validation_errors = errors return errors
[ "def", "validate_schema", "(", "schema", ":", "GraphQLSchema", ")", "->", "List", "[", "GraphQLError", "]", ":", "# First check to ensure the provided value is in fact a GraphQLSchema.", "assert_schema", "(", "schema", ")", "# If this Schema has already been validated, return the...
Validate a GraphQL schema. Implements the "Type Validation" sub-sections of the specification's "Type System" section. Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the Schema is valid.
[ "Validate", "a", "GraphQL", "schema", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/validate.py#L40-L68
226,144
graphql-python/graphql-core-next
graphql/type/validate.py
assert_valid_schema
def assert_valid_schema(schema: GraphQLSchema) -> None: """Utility function which asserts a schema is valid. Throws a TypeError if the schema is invalid. """ errors = validate_schema(schema) if errors: raise TypeError("\n\n".join(error.message for error in errors))
python
def assert_valid_schema(schema: GraphQLSchema) -> None: errors = validate_schema(schema) if errors: raise TypeError("\n\n".join(error.message for error in errors))
[ "def", "assert_valid_schema", "(", "schema", ":", "GraphQLSchema", ")", "->", "None", ":", "errors", "=", "validate_schema", "(", "schema", ")", "if", "errors", ":", "raise", "TypeError", "(", "\"\\n\\n\"", ".", "join", "(", "error", ".", "message", "for", ...
Utility function which asserts a schema is valid. Throws a TypeError if the schema is invalid.
[ "Utility", "function", "which", "asserts", "a", "schema", "is", "valid", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/validate.py#L71-L78
226,145
graphql-python/graphql-core-next
graphql/utilities/separate_operations.py
separate_operations
def separate_operations(document_ast: DocumentNode) -> Dict[str, DocumentNode]: """Separate operations in a given AST document. This function accepts a single AST document which may contain many operations and fragments and returns a collection of AST documents each of which contains a single operation as well the fragment definitions it refers to. """ # Populate metadata and build a dependency graph. visitor = SeparateOperations() visit(document_ast, visitor) operations = visitor.operations fragments = visitor.fragments positions = visitor.positions dep_graph = visitor.dep_graph # For each operation, produce a new synthesized AST which includes only what is # necessary for completing that operation. separated_document_asts = {} for operation in operations: operation_name = op_name(operation) dependencies: Set[str] = set() collect_transitive_dependencies(dependencies, dep_graph, operation_name) # The list of definition nodes to be included for this operation, sorted to # retain the same order as the original document. definitions: List[ExecutableDefinitionNode] = [operation] for name in dependencies: definitions.append(fragments[name]) definitions.sort(key=lambda n: positions.get(n, 0)) separated_document_asts[operation_name] = DocumentNode(definitions=definitions) return separated_document_asts
python
def separate_operations(document_ast: DocumentNode) -> Dict[str, DocumentNode]: # Populate metadata and build a dependency graph. visitor = SeparateOperations() visit(document_ast, visitor) operations = visitor.operations fragments = visitor.fragments positions = visitor.positions dep_graph = visitor.dep_graph # For each operation, produce a new synthesized AST which includes only what is # necessary for completing that operation. separated_document_asts = {} for operation in operations: operation_name = op_name(operation) dependencies: Set[str] = set() collect_transitive_dependencies(dependencies, dep_graph, operation_name) # The list of definition nodes to be included for this operation, sorted to # retain the same order as the original document. definitions: List[ExecutableDefinitionNode] = [operation] for name in dependencies: definitions.append(fragments[name]) definitions.sort(key=lambda n: positions.get(n, 0)) separated_document_asts[operation_name] = DocumentNode(definitions=definitions) return separated_document_asts
[ "def", "separate_operations", "(", "document_ast", ":", "DocumentNode", ")", "->", "Dict", "[", "str", ",", "DocumentNode", "]", ":", "# Populate metadata and build a dependency graph.", "visitor", "=", "SeparateOperations", "(", ")", "visit", "(", "document_ast", ","...
Separate operations in a given AST document. This function accepts a single AST document which may contain many operations and fragments and returns a collection of AST documents each of which contains a single operation as well the fragment definitions it refers to.
[ "Separate", "operations", "in", "a", "given", "AST", "document", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/separate_operations.py#L19-L52
226,146
graphql-python/graphql-core-next
graphql/utilities/separate_operations.py
collect_transitive_dependencies
def collect_transitive_dependencies( collected: Set[str], dep_graph: DepGraph, from_name: str ) -> None: """Collect transitive dependencies. From a dependency graph, collects a list of transitive dependencies by recursing through a dependency graph. """ immediate_deps = dep_graph[from_name] for to_name in immediate_deps: if to_name not in collected: collected.add(to_name) collect_transitive_dependencies(collected, dep_graph, to_name)
python
def collect_transitive_dependencies( collected: Set[str], dep_graph: DepGraph, from_name: str ) -> None: immediate_deps = dep_graph[from_name] for to_name in immediate_deps: if to_name not in collected: collected.add(to_name) collect_transitive_dependencies(collected, dep_graph, to_name)
[ "def", "collect_transitive_dependencies", "(", "collected", ":", "Set", "[", "str", "]", ",", "dep_graph", ":", "DepGraph", ",", "from_name", ":", "str", ")", "->", "None", ":", "immediate_deps", "=", "dep_graph", "[", "from_name", "]", "for", "to_name", "in...
Collect transitive dependencies. From a dependency graph, collects a list of transitive dependencies by recursing through a dependency graph.
[ "Collect", "transitive", "dependencies", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/separate_operations.py#L87-L99
226,147
graphql-python/graphql-core-next
graphql/utilities/ast_from_value.py
ast_from_value
def ast_from_value(value: Any, type_: GraphQLInputType) -> Optional[ValueNode]: """Produce a GraphQL Value AST given a Python value. A GraphQL type must be provided, which will be used to interpret different Python values. | JSON Value | GraphQL Value | | ------------- | -------------------- | | Object | Input Object | | Array | List | | Boolean | Boolean | | String | String / Enum Value | | Number | Int / Float | | Mixed | Enum Value | | null | NullValue | """ if is_non_null_type(type_): type_ = cast(GraphQLNonNull, type_) ast_value = ast_from_value(value, type_.of_type) if isinstance(ast_value, NullValueNode): return None return ast_value # only explicit None, not INVALID or NaN if value is None: return NullValueNode() # INVALID or NaN if is_invalid(value): return None # Convert Python list to GraphQL list. If the GraphQLType is a list, but the value # is not a list, convert the value using the list's item type. if is_list_type(type_): type_ = cast(GraphQLList, type_) item_type = type_.of_type if isinstance(value, Iterable) and not isinstance(value, str): value_nodes = [ ast_from_value(item, item_type) for item in value # type: ignore ] return ListValueNode(values=value_nodes) return ast_from_value(value, item_type) # type: ignore # Populate the fields of the input object by creating ASTs from each value in the # Python dict according to the fields in the input type. if is_input_object_type(type_): if value is None or not isinstance(value, Mapping): return None type_ = cast(GraphQLInputObjectType, type_) field_nodes: List[ObjectFieldNode] = [] append_node = field_nodes.append for field_name, field in type_.fields.items(): if field_name in value: field_value = ast_from_value(value[field_name], field.type) if field_value: append_node( ObjectFieldNode( name=NameNode(value=field_name), value=field_value ) ) return ObjectValueNode(fields=field_nodes) if is_leaf_type(type_): # Since value is an internally represented value, it must be serialized to an # externally represented value before converting into an AST. serialized = type_.serialize(value) # type: ignore if is_nullish(serialized): return None # Others serialize based on their corresponding Python scalar types. if isinstance(serialized, bool): return BooleanValueNode(value=serialized) # Python ints and floats correspond nicely to Int and Float values. if isinstance(serialized, int): return IntValueNode(value=f"{serialized:d}") if isinstance(serialized, float): return FloatValueNode(value=f"{serialized:g}") if isinstance(serialized, str): # Enum types use Enum literals. if is_enum_type(type_): return EnumValueNode(value=serialized) # ID types can use Int literals. if type_ is GraphQLID and _re_integer_string.match(serialized): return IntValueNode(value=serialized) return StringValueNode(value=serialized) raise TypeError(f"Cannot convert value to AST: {inspect(serialized)}") # Not reachable. All possible input types have been considered. raise TypeError(f"Unexpected input type: '{inspect(type_)}'.")
python
def ast_from_value(value: Any, type_: GraphQLInputType) -> Optional[ValueNode]: if is_non_null_type(type_): type_ = cast(GraphQLNonNull, type_) ast_value = ast_from_value(value, type_.of_type) if isinstance(ast_value, NullValueNode): return None return ast_value # only explicit None, not INVALID or NaN if value is None: return NullValueNode() # INVALID or NaN if is_invalid(value): return None # Convert Python list to GraphQL list. If the GraphQLType is a list, but the value # is not a list, convert the value using the list's item type. if is_list_type(type_): type_ = cast(GraphQLList, type_) item_type = type_.of_type if isinstance(value, Iterable) and not isinstance(value, str): value_nodes = [ ast_from_value(item, item_type) for item in value # type: ignore ] return ListValueNode(values=value_nodes) return ast_from_value(value, item_type) # type: ignore # Populate the fields of the input object by creating ASTs from each value in the # Python dict according to the fields in the input type. if is_input_object_type(type_): if value is None or not isinstance(value, Mapping): return None type_ = cast(GraphQLInputObjectType, type_) field_nodes: List[ObjectFieldNode] = [] append_node = field_nodes.append for field_name, field in type_.fields.items(): if field_name in value: field_value = ast_from_value(value[field_name], field.type) if field_value: append_node( ObjectFieldNode( name=NameNode(value=field_name), value=field_value ) ) return ObjectValueNode(fields=field_nodes) if is_leaf_type(type_): # Since value is an internally represented value, it must be serialized to an # externally represented value before converting into an AST. serialized = type_.serialize(value) # type: ignore if is_nullish(serialized): return None # Others serialize based on their corresponding Python scalar types. if isinstance(serialized, bool): return BooleanValueNode(value=serialized) # Python ints and floats correspond nicely to Int and Float values. if isinstance(serialized, int): return IntValueNode(value=f"{serialized:d}") if isinstance(serialized, float): return FloatValueNode(value=f"{serialized:g}") if isinstance(serialized, str): # Enum types use Enum literals. if is_enum_type(type_): return EnumValueNode(value=serialized) # ID types can use Int literals. if type_ is GraphQLID and _re_integer_string.match(serialized): return IntValueNode(value=serialized) return StringValueNode(value=serialized) raise TypeError(f"Cannot convert value to AST: {inspect(serialized)}") # Not reachable. All possible input types have been considered. raise TypeError(f"Unexpected input type: '{inspect(type_)}'.")
[ "def", "ast_from_value", "(", "value", ":", "Any", ",", "type_", ":", "GraphQLInputType", ")", "->", "Optional", "[", "ValueNode", "]", ":", "if", "is_non_null_type", "(", "type_", ")", ":", "type_", "=", "cast", "(", "GraphQLNonNull", ",", "type_", ")", ...
Produce a GraphQL Value AST given a Python value. A GraphQL type must be provided, which will be used to interpret different Python values. | JSON Value | GraphQL Value | | ------------- | -------------------- | | Object | Input Object | | Array | List | | Boolean | Boolean | | String | String / Enum Value | | Number | Int / Float | | Mixed | Enum Value | | null | NullValue |
[ "Produce", "a", "GraphQL", "Value", "AST", "given", "a", "Python", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/ast_from_value.py#L36-L130
226,148
graphql-python/graphql-core-next
graphql/execution/values.py
get_variable_values
def get_variable_values( schema: GraphQLSchema, var_def_nodes: List[VariableDefinitionNode], inputs: Dict[str, Any], ) -> CoercedVariableValues: """Get coerced variable values based on provided definitions. Prepares a dict of variable values of the correct type based on the provided variable definitions and arbitrary input. If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown. """ errors: List[GraphQLError] = [] coerced_values: Dict[str, Any] = {} for var_def_node in var_def_nodes: var_name = var_def_node.variable.name.value var_type = type_from_ast(schema, var_def_node.type) if not is_input_type(var_type): # Must use input types for variables. This should be caught during # validation, however is checked again here for safety. errors.append( GraphQLError( f"Variable '${var_name}' expected value of type" f" '{print_ast(var_def_node.type)}'" " which cannot be used as an input type.", var_def_node.type, ) ) else: var_type = cast(GraphQLInputType, var_type) has_value = var_name in inputs value = inputs[var_name] if has_value else INVALID if not has_value and var_def_node.default_value: # If no value was provided to a variable with a default value, use the # default value. coerced_values[var_name] = value_from_ast( var_def_node.default_value, var_type ) elif (not has_value or value is None) and is_non_null_type(var_type): errors.append( GraphQLError( f"Variable '${var_name}' of non-null type" f" '{var_type}' must not be null." if has_value else f"Variable '${var_name}' of required type" f" '{var_type}' was not provided.", var_def_node, ) ) elif has_value: if value is None: # If the explicit value `None` was provided, an entry in the # coerced values must exist as the value `None`. coerced_values[var_name] = None else: # Otherwise, a non-null value was provided, coerce it to the # expected type or report an error if coercion fails. coerced = coerce_value(value, var_type, var_def_node) coercion_errors = coerced.errors if coercion_errors: for error in coercion_errors: error.message = ( f"Variable '${var_name}' got invalid" f" value {inspect(value)}; {error.message}" ) errors.extend(coercion_errors) else: coerced_values[var_name] = coerced.value return ( CoercedVariableValues(errors, None) if errors else CoercedVariableValues(None, coerced_values) )
python
def get_variable_values( schema: GraphQLSchema, var_def_nodes: List[VariableDefinitionNode], inputs: Dict[str, Any], ) -> CoercedVariableValues: errors: List[GraphQLError] = [] coerced_values: Dict[str, Any] = {} for var_def_node in var_def_nodes: var_name = var_def_node.variable.name.value var_type = type_from_ast(schema, var_def_node.type) if not is_input_type(var_type): # Must use input types for variables. This should be caught during # validation, however is checked again here for safety. errors.append( GraphQLError( f"Variable '${var_name}' expected value of type" f" '{print_ast(var_def_node.type)}'" " which cannot be used as an input type.", var_def_node.type, ) ) else: var_type = cast(GraphQLInputType, var_type) has_value = var_name in inputs value = inputs[var_name] if has_value else INVALID if not has_value and var_def_node.default_value: # If no value was provided to a variable with a default value, use the # default value. coerced_values[var_name] = value_from_ast( var_def_node.default_value, var_type ) elif (not has_value or value is None) and is_non_null_type(var_type): errors.append( GraphQLError( f"Variable '${var_name}' of non-null type" f" '{var_type}' must not be null." if has_value else f"Variable '${var_name}' of required type" f" '{var_type}' was not provided.", var_def_node, ) ) elif has_value: if value is None: # If the explicit value `None` was provided, an entry in the # coerced values must exist as the value `None`. coerced_values[var_name] = None else: # Otherwise, a non-null value was provided, coerce it to the # expected type or report an error if coercion fails. coerced = coerce_value(value, var_type, var_def_node) coercion_errors = coerced.errors if coercion_errors: for error in coercion_errors: error.message = ( f"Variable '${var_name}' got invalid" f" value {inspect(value)}; {error.message}" ) errors.extend(coercion_errors) else: coerced_values[var_name] = coerced.value return ( CoercedVariableValues(errors, None) if errors else CoercedVariableValues(None, coerced_values) )
[ "def", "get_variable_values", "(", "schema", ":", "GraphQLSchema", ",", "var_def_nodes", ":", "List", "[", "VariableDefinitionNode", "]", ",", "inputs", ":", "Dict", "[", "str", ",", "Any", "]", ",", ")", "->", "CoercedVariableValues", ":", "errors", ":", "L...
Get coerced variable values based on provided definitions. Prepares a dict of variable values of the correct type based on the provided variable definitions and arbitrary input. If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown.
[ "Get", "coerced", "variable", "values", "based", "on", "provided", "definitions", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/values.py#L37-L108
226,149
graphql-python/graphql-core-next
graphql/execution/values.py
get_argument_values
def get_argument_values( type_def: Union[GraphQLField, GraphQLDirective], node: Union[FieldNode, DirectiveNode], variable_values: Dict[str, Any] = None, ) -> Dict[str, Any]: """Get coerced argument values based on provided definitions and nodes. Prepares an dict of argument values given a list of argument definitions and list of argument AST nodes. """ coerced_values: Dict[str, Any] = {} arg_defs = type_def.args arg_nodes = node.arguments if not arg_defs or arg_nodes is None: return coerced_values arg_node_map = {arg.name.value: arg for arg in arg_nodes} for name, arg_def in arg_defs.items(): arg_type = arg_def.type argument_node = cast(ArgumentNode, arg_node_map.get(name)) variable_values = cast(Dict[str, Any], variable_values) if argument_node and isinstance(argument_node.value, VariableNode): variable_name = argument_node.value.name.value has_value = variable_values and variable_name in variable_values is_null = has_value and variable_values[variable_name] is None else: has_value = argument_node is not None is_null = has_value and isinstance(argument_node.value, NullValueNode) if not has_value and arg_def.default_value is not INVALID: # If no argument was provided where the definition has a default value, # use the default value. coerced_values[name] = arg_def.default_value elif (not has_value or is_null) and is_non_null_type(arg_type): # If no argument or a null value was provided to an argument with a non-null # type (required), produce a field error. if is_null: raise GraphQLError( f"Argument '{name}' of non-null type" f" '{arg_type}' must not be null.", argument_node.value, ) elif argument_node and isinstance(argument_node.value, VariableNode): raise GraphQLError( f"Argument '{name}' of required type" f" '{arg_type}' was provided the variable" f" '${variable_name}'" " which was not provided a runtime value.", argument_node.value, ) else: raise GraphQLError( f"Argument '{name}' of required type '{arg_type}'" " was not provided.", node, ) elif has_value: if isinstance(argument_node.value, NullValueNode): # If the explicit value `None` was provided, an entry in the coerced # values must exist as the value `None`. coerced_values[name] = None elif isinstance(argument_node.value, VariableNode): variable_name = argument_node.value.name.value # Note: This Does no further checking that this variable is correct. # This assumes that this query has been validated and the variable # usage here is of the correct type. coerced_values[name] = variable_values[variable_name] else: value_node = argument_node.value coerced_value = value_from_ast(value_node, arg_type, variable_values) if coerced_value is INVALID: # Note: `values_of_correct_type` validation should catch this before # execution. This is a runtime check to ensure execution does not # continue with an invalid argument value. raise GraphQLError( f"Argument '{name}'" f" has invalid value {print_ast(value_node)}.", argument_node.value, ) coerced_values[name] = coerced_value return coerced_values
python
def get_argument_values( type_def: Union[GraphQLField, GraphQLDirective], node: Union[FieldNode, DirectiveNode], variable_values: Dict[str, Any] = None, ) -> Dict[str, Any]: coerced_values: Dict[str, Any] = {} arg_defs = type_def.args arg_nodes = node.arguments if not arg_defs or arg_nodes is None: return coerced_values arg_node_map = {arg.name.value: arg for arg in arg_nodes} for name, arg_def in arg_defs.items(): arg_type = arg_def.type argument_node = cast(ArgumentNode, arg_node_map.get(name)) variable_values = cast(Dict[str, Any], variable_values) if argument_node and isinstance(argument_node.value, VariableNode): variable_name = argument_node.value.name.value has_value = variable_values and variable_name in variable_values is_null = has_value and variable_values[variable_name] is None else: has_value = argument_node is not None is_null = has_value and isinstance(argument_node.value, NullValueNode) if not has_value and arg_def.default_value is not INVALID: # If no argument was provided where the definition has a default value, # use the default value. coerced_values[name] = arg_def.default_value elif (not has_value or is_null) and is_non_null_type(arg_type): # If no argument or a null value was provided to an argument with a non-null # type (required), produce a field error. if is_null: raise GraphQLError( f"Argument '{name}' of non-null type" f" '{arg_type}' must not be null.", argument_node.value, ) elif argument_node and isinstance(argument_node.value, VariableNode): raise GraphQLError( f"Argument '{name}' of required type" f" '{arg_type}' was provided the variable" f" '${variable_name}'" " which was not provided a runtime value.", argument_node.value, ) else: raise GraphQLError( f"Argument '{name}' of required type '{arg_type}'" " was not provided.", node, ) elif has_value: if isinstance(argument_node.value, NullValueNode): # If the explicit value `None` was provided, an entry in the coerced # values must exist as the value `None`. coerced_values[name] = None elif isinstance(argument_node.value, VariableNode): variable_name = argument_node.value.name.value # Note: This Does no further checking that this variable is correct. # This assumes that this query has been validated and the variable # usage here is of the correct type. coerced_values[name] = variable_values[variable_name] else: value_node = argument_node.value coerced_value = value_from_ast(value_node, arg_type, variable_values) if coerced_value is INVALID: # Note: `values_of_correct_type` validation should catch this before # execution. This is a runtime check to ensure execution does not # continue with an invalid argument value. raise GraphQLError( f"Argument '{name}'" f" has invalid value {print_ast(value_node)}.", argument_node.value, ) coerced_values[name] = coerced_value return coerced_values
[ "def", "get_argument_values", "(", "type_def", ":", "Union", "[", "GraphQLField", ",", "GraphQLDirective", "]", ",", "node", ":", "Union", "[", "FieldNode", ",", "DirectiveNode", "]", ",", "variable_values", ":", "Dict", "[", "str", ",", "Any", "]", "=", "...
Get coerced argument values based on provided definitions and nodes. Prepares an dict of argument values given a list of argument definitions and list of argument AST nodes.
[ "Get", "coerced", "argument", "values", "based", "on", "provided", "definitions", "and", "nodes", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/values.py#L111-L189
226,150
graphql-python/graphql-core-next
graphql/execution/values.py
get_directive_values
def get_directive_values( directive_def: GraphQLDirective, node: NodeWithDirective, variable_values: Dict[str, Any] = None, ) -> Optional[Dict[str, Any]]: """Get coerced argument values based on provided nodes. Prepares a dict of argument values given a directive definition and an AST node which may contain directives. Optionally also accepts a dict of variable values. If the directive does not exist on the node, returns None. """ directives = node.directives if directives: directive_name = directive_def.name for directive in directives: if directive.name.value == directive_name: return get_argument_values(directive_def, directive, variable_values) return None
python
def get_directive_values( directive_def: GraphQLDirective, node: NodeWithDirective, variable_values: Dict[str, Any] = None, ) -> Optional[Dict[str, Any]]: directives = node.directives if directives: directive_name = directive_def.name for directive in directives: if directive.name.value == directive_name: return get_argument_values(directive_def, directive, variable_values) return None
[ "def", "get_directive_values", "(", "directive_def", ":", "GraphQLDirective", ",", "node", ":", "NodeWithDirective", ",", "variable_values", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "A...
Get coerced argument values based on provided nodes. Prepares a dict of argument values given a directive definition and an AST node which may contain directives. Optionally also accepts a dict of variable values. If the directive does not exist on the node, returns None.
[ "Get", "coerced", "argument", "values", "based", "on", "provided", "nodes", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/values.py#L201-L219
226,151
graphql-python/graphql-core-next
graphql/utilities/build_ast_schema.py
build_ast_schema
def build_ast_schema( document_ast: DocumentNode, assume_valid: bool = False, assume_valid_sdl: bool = False, ) -> GraphQLSchema: """Build a GraphQL Schema from a given AST. This takes the ast of a schema document produced by the parse function in src/language/parser.py. If no schema definition is provided, then it will look for types named Query and Mutation. Given that AST it constructs a GraphQLSchema. The resulting schema has no resolve methods, so execution will use default resolvers. When building a schema from a GraphQL service's introspection result, it might be safe to assume the schema is valid. Set `assume_valid` to True to assume the produced schema is valid. Set `assume_valid_sdl` to True to assume it is already a valid SDL document. """ if not isinstance(document_ast, DocumentNode): raise TypeError("Must provide a Document AST.") if not (assume_valid or assume_valid_sdl): from ..validation.validate import assert_valid_sdl assert_valid_sdl(document_ast) schema_def: Optional[SchemaDefinitionNode] = None type_defs: List[TypeDefinitionNode] = [] directive_defs: List[DirectiveDefinitionNode] = [] append_directive_def = directive_defs.append for def_ in document_ast.definitions: if isinstance(def_, SchemaDefinitionNode): schema_def = def_ elif isinstance(def_, TypeDefinitionNode): def_ = cast(TypeDefinitionNode, def_) type_defs.append(def_) elif isinstance(def_, DirectiveDefinitionNode): append_directive_def(def_) def resolve_type(type_name: str) -> GraphQLNamedType: type_ = type_map.get(type_name) if not type: raise TypeError(f"Type '{type_name}' not found in document.") return type_ ast_builder = ASTDefinitionBuilder( assume_valid=assume_valid, resolve_type=resolve_type ) type_map = {node.name.value: ast_builder.build_type(node) for node in type_defs} if schema_def: operation_types = get_operation_types(schema_def) else: operation_types = { OperationType.QUERY: "Query", OperationType.MUTATION: "Mutation", OperationType.SUBSCRIPTION: "Subscription", } directives = [ ast_builder.build_directive(directive_def) for directive_def in directive_defs ] # If specified directives were not explicitly declared, add them. if not any(directive.name == "skip" for directive in directives): directives.append(GraphQLSkipDirective) if not any(directive.name == "include" for directive in directives): directives.append(GraphQLIncludeDirective) if not any(directive.name == "deprecated" for directive in directives): directives.append(GraphQLDeprecatedDirective) query_type = operation_types.get(OperationType.QUERY) mutation_type = operation_types.get(OperationType.MUTATION) subscription_type = operation_types.get(OperationType.SUBSCRIPTION) return GraphQLSchema( # Note: While this could make early assertions to get the correctly # typed values below, that would throw immediately while type system # validation with `validate_schema()` will produce more actionable results. query=cast(GraphQLObjectType, type_map.get(query_type)) if query_type else None, mutation=cast(GraphQLObjectType, type_map.get(mutation_type)) if mutation_type else None, subscription=cast(GraphQLObjectType, type_map.get(subscription_type)) if subscription_type else None, types=list(type_map.values()), directives=directives, ast_node=schema_def, assume_valid=assume_valid, )
python
def build_ast_schema( document_ast: DocumentNode, assume_valid: bool = False, assume_valid_sdl: bool = False, ) -> GraphQLSchema: if not isinstance(document_ast, DocumentNode): raise TypeError("Must provide a Document AST.") if not (assume_valid or assume_valid_sdl): from ..validation.validate import assert_valid_sdl assert_valid_sdl(document_ast) schema_def: Optional[SchemaDefinitionNode] = None type_defs: List[TypeDefinitionNode] = [] directive_defs: List[DirectiveDefinitionNode] = [] append_directive_def = directive_defs.append for def_ in document_ast.definitions: if isinstance(def_, SchemaDefinitionNode): schema_def = def_ elif isinstance(def_, TypeDefinitionNode): def_ = cast(TypeDefinitionNode, def_) type_defs.append(def_) elif isinstance(def_, DirectiveDefinitionNode): append_directive_def(def_) def resolve_type(type_name: str) -> GraphQLNamedType: type_ = type_map.get(type_name) if not type: raise TypeError(f"Type '{type_name}' not found in document.") return type_ ast_builder = ASTDefinitionBuilder( assume_valid=assume_valid, resolve_type=resolve_type ) type_map = {node.name.value: ast_builder.build_type(node) for node in type_defs} if schema_def: operation_types = get_operation_types(schema_def) else: operation_types = { OperationType.QUERY: "Query", OperationType.MUTATION: "Mutation", OperationType.SUBSCRIPTION: "Subscription", } directives = [ ast_builder.build_directive(directive_def) for directive_def in directive_defs ] # If specified directives were not explicitly declared, add them. if not any(directive.name == "skip" for directive in directives): directives.append(GraphQLSkipDirective) if not any(directive.name == "include" for directive in directives): directives.append(GraphQLIncludeDirective) if not any(directive.name == "deprecated" for directive in directives): directives.append(GraphQLDeprecatedDirective) query_type = operation_types.get(OperationType.QUERY) mutation_type = operation_types.get(OperationType.MUTATION) subscription_type = operation_types.get(OperationType.SUBSCRIPTION) return GraphQLSchema( # Note: While this could make early assertions to get the correctly # typed values below, that would throw immediately while type system # validation with `validate_schema()` will produce more actionable results. query=cast(GraphQLObjectType, type_map.get(query_type)) if query_type else None, mutation=cast(GraphQLObjectType, type_map.get(mutation_type)) if mutation_type else None, subscription=cast(GraphQLObjectType, type_map.get(subscription_type)) if subscription_type else None, types=list(type_map.values()), directives=directives, ast_node=schema_def, assume_valid=assume_valid, )
[ "def", "build_ast_schema", "(", "document_ast", ":", "DocumentNode", ",", "assume_valid", ":", "bool", "=", "False", ",", "assume_valid_sdl", ":", "bool", "=", "False", ",", ")", "->", "GraphQLSchema", ":", "if", "not", "isinstance", "(", "document_ast", ",", ...
Build a GraphQL Schema from a given AST. This takes the ast of a schema document produced by the parse function in src/language/parser.py. If no schema definition is provided, then it will look for types named Query and Mutation. Given that AST it constructs a GraphQLSchema. The resulting schema has no resolve methods, so execution will use default resolvers. When building a schema from a GraphQL service's introspection result, it might be safe to assume the schema is valid. Set `assume_valid` to True to assume the produced schema is valid. Set `assume_valid_sdl` to True to assume it is already a valid SDL document.
[ "Build", "a", "GraphQL", "Schema", "from", "a", "given", "AST", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/build_ast_schema.py#L71-L164
226,152
graphql-python/graphql-core-next
graphql/utilities/build_ast_schema.py
get_deprecation_reason
def get_deprecation_reason( node: Union[EnumValueDefinitionNode, FieldDefinitionNode] ) -> Optional[str]: """Given a field or enum value node, get deprecation reason as string.""" from ..execution import get_directive_values deprecated = get_directive_values(GraphQLDeprecatedDirective, node) return deprecated["reason"] if deprecated else None
python
def get_deprecation_reason( node: Union[EnumValueDefinitionNode, FieldDefinitionNode] ) -> Optional[str]: from ..execution import get_directive_values deprecated = get_directive_values(GraphQLDeprecatedDirective, node) return deprecated["reason"] if deprecated else None
[ "def", "get_deprecation_reason", "(", "node", ":", "Union", "[", "EnumValueDefinitionNode", ",", "FieldDefinitionNode", "]", ")", "->", "Optional", "[", "str", "]", ":", "from", ".", ".", "execution", "import", "get_directive_values", "deprecated", "=", "get_direc...
Given a field or enum value node, get deprecation reason as string.
[ "Given", "a", "field", "or", "enum", "value", "node", "get", "deprecation", "reason", "as", "string", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/build_ast_schema.py#L416-L423
226,153
graphql-python/graphql-core-next
graphql/utilities/build_ast_schema.py
build_schema
def build_schema( source: Union[str, Source], assume_valid=False, assume_valid_sdl=False, no_location=False, experimental_fragment_variables=False, ) -> GraphQLSchema: """Build a GraphQLSchema directly from a source document.""" return build_ast_schema( parse( source, no_location=no_location, experimental_fragment_variables=experimental_fragment_variables, ), assume_valid=assume_valid, assume_valid_sdl=assume_valid_sdl, )
python
def build_schema( source: Union[str, Source], assume_valid=False, assume_valid_sdl=False, no_location=False, experimental_fragment_variables=False, ) -> GraphQLSchema: return build_ast_schema( parse( source, no_location=no_location, experimental_fragment_variables=experimental_fragment_variables, ), assume_valid=assume_valid, assume_valid_sdl=assume_valid_sdl, )
[ "def", "build_schema", "(", "source", ":", "Union", "[", "str", ",", "Source", "]", ",", "assume_valid", "=", "False", ",", "assume_valid_sdl", "=", "False", ",", "no_location", "=", "False", ",", "experimental_fragment_variables", "=", "False", ",", ")", "-...
Build a GraphQLSchema directly from a source document.
[ "Build", "a", "GraphQLSchema", "directly", "from", "a", "source", "document", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/build_ast_schema.py#L435-L451
226,154
graphql-python/graphql-core-next
graphql/validation/validate.py
validate
def validate( schema: GraphQLSchema, document_ast: DocumentNode, rules: Sequence[RuleType] = None, type_info: TypeInfo = None, ) -> List[GraphQLError]: """Implements the "Validation" section of the spec. Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the document is valid. A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used. Each validation rule is a ValidationRule object which is a visitor object that holds a ValidationContext (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or lists of GraphQLErrors when invalid. Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema. """ if not document_ast or not isinstance(document_ast, DocumentNode): raise TypeError("You must provide a document node.") # If the schema used for validation is invalid, throw an error. assert_valid_schema(schema) if type_info is None: type_info = TypeInfo(schema) elif not isinstance(type_info, TypeInfo): raise TypeError(f"Not a TypeInfo object: {inspect(type_info)}") if rules is None: rules = specified_rules elif not isinstance(rules, (list, tuple)): raise TypeError("Rules must be passed as a list/tuple.") context = ValidationContext(schema, document_ast, type_info) # This uses a specialized visitor which runs multiple visitors in parallel, # while maintaining the visitor skip and break API. visitors = [rule(context) for rule in rules] # Visit the whole document with each instance of all provided rules. visit(document_ast, TypeInfoVisitor(type_info, ParallelVisitor(visitors))) return context.errors
python
def validate( schema: GraphQLSchema, document_ast: DocumentNode, rules: Sequence[RuleType] = None, type_info: TypeInfo = None, ) -> List[GraphQLError]: if not document_ast or not isinstance(document_ast, DocumentNode): raise TypeError("You must provide a document node.") # If the schema used for validation is invalid, throw an error. assert_valid_schema(schema) if type_info is None: type_info = TypeInfo(schema) elif not isinstance(type_info, TypeInfo): raise TypeError(f"Not a TypeInfo object: {inspect(type_info)}") if rules is None: rules = specified_rules elif not isinstance(rules, (list, tuple)): raise TypeError("Rules must be passed as a list/tuple.") context = ValidationContext(schema, document_ast, type_info) # This uses a specialized visitor which runs multiple visitors in parallel, # while maintaining the visitor skip and break API. visitors = [rule(context) for rule in rules] # Visit the whole document with each instance of all provided rules. visit(document_ast, TypeInfoVisitor(type_info, ParallelVisitor(visitors))) return context.errors
[ "def", "validate", "(", "schema", ":", "GraphQLSchema", ",", "document_ast", ":", "DocumentNode", ",", "rules", ":", "Sequence", "[", "RuleType", "]", "=", "None", ",", "type_info", ":", "TypeInfo", "=", "None", ",", ")", "->", "List", "[", "GraphQLError",...
Implements the "Validation" section of the spec. Validation runs synchronously, returning a list of encountered errors, or an empty list if no errors were encountered and the document is valid. A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used. Each validation rule is a ValidationRule object which is a visitor object that holds a ValidationContext (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or lists of GraphQLErrors when invalid. Optionally a custom TypeInfo instance may be provided. If not provided, one will be created from the provided schema.
[ "Implements", "the", "Validation", "section", "of", "the", "spec", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/validate.py#L15-L54
226,155
graphql-python/graphql-core-next
graphql/validation/validate.py
validate_sdl
def validate_sdl( document_ast: DocumentNode, schema_to_extend: GraphQLSchema = None, rules: Sequence[RuleType] = None, ) -> List[GraphQLError]: """Validate an SDL document.""" context = SDLValidationContext(document_ast, schema_to_extend) if rules is None: rules = specified_sdl_rules visitors = [rule(context) for rule in rules] visit(document_ast, ParallelVisitor(visitors)) return context.errors
python
def validate_sdl( document_ast: DocumentNode, schema_to_extend: GraphQLSchema = None, rules: Sequence[RuleType] = None, ) -> List[GraphQLError]: context = SDLValidationContext(document_ast, schema_to_extend) if rules is None: rules = specified_sdl_rules visitors = [rule(context) for rule in rules] visit(document_ast, ParallelVisitor(visitors)) return context.errors
[ "def", "validate_sdl", "(", "document_ast", ":", "DocumentNode", ",", "schema_to_extend", ":", "GraphQLSchema", "=", "None", ",", "rules", ":", "Sequence", "[", "RuleType", "]", "=", "None", ",", ")", "->", "List", "[", "GraphQLError", "]", ":", "context", ...
Validate an SDL document.
[ "Validate", "an", "SDL", "document", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/validate.py#L57-L68
226,156
graphql-python/graphql-core-next
graphql/validation/validate.py
assert_valid_sdl
def assert_valid_sdl(document_ast: DocumentNode) -> None: """Assert document is valid SDL. Utility function which asserts a SDL document is valid by throwing an error if it is invalid. """ errors = validate_sdl(document_ast) if errors: raise TypeError("\n\n".join(error.message for error in errors))
python
def assert_valid_sdl(document_ast: DocumentNode) -> None: errors = validate_sdl(document_ast) if errors: raise TypeError("\n\n".join(error.message for error in errors))
[ "def", "assert_valid_sdl", "(", "document_ast", ":", "DocumentNode", ")", "->", "None", ":", "errors", "=", "validate_sdl", "(", "document_ast", ")", "if", "errors", ":", "raise", "TypeError", "(", "\"\\n\\n\"", ".", "join", "(", "error", ".", "message", "fo...
Assert document is valid SDL. Utility function which asserts a SDL document is valid by throwing an error if it is invalid.
[ "Assert", "document", "is", "valid", "SDL", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/validate.py#L71-L80
226,157
graphql-python/graphql-core-next
graphql/validation/validate.py
assert_valid_sdl_extension
def assert_valid_sdl_extension( document_ast: DocumentNode, schema: GraphQLSchema ) -> None: """Assert document is a valid SDL extension. Utility function which asserts a SDL document is valid by throwing an error if it is invalid. """ errors = validate_sdl(document_ast, schema) if errors: raise TypeError("\n\n".join(error.message for error in errors))
python
def assert_valid_sdl_extension( document_ast: DocumentNode, schema: GraphQLSchema ) -> None: errors = validate_sdl(document_ast, schema) if errors: raise TypeError("\n\n".join(error.message for error in errors))
[ "def", "assert_valid_sdl_extension", "(", "document_ast", ":", "DocumentNode", ",", "schema", ":", "GraphQLSchema", ")", "->", "None", ":", "errors", "=", "validate_sdl", "(", "document_ast", ",", "schema", ")", "if", "errors", ":", "raise", "TypeError", "(", ...
Assert document is a valid SDL extension. Utility function which asserts a SDL document is valid by throwing an error if it is invalid.
[ "Assert", "document", "is", "a", "valid", "SDL", "extension", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/validate.py#L83-L94
226,158
graphql-python/graphql-core-next
graphql/utilities/type_from_ast.py
type_from_ast
def type_from_ast(schema, type_node): # noqa: F811 """Get the GraphQL type definition from an AST node. Given a Schema and an AST node describing a type, return a GraphQLType definition which applies to that type. For example, if provided the parsed AST node for `[User]`, a GraphQLList instance will be returned, containing the type called "User" found in the schema. If a type called "User" is not found in the schema, then None will be returned. """ if isinstance(type_node, ListTypeNode): inner_type = type_from_ast(schema, type_node.type) return GraphQLList(inner_type) if inner_type else None if isinstance(type_node, NonNullTypeNode): inner_type = type_from_ast(schema, type_node.type) return GraphQLNonNull(inner_type) if inner_type else None if isinstance(type_node, NamedTypeNode): return schema.get_type(type_node.name.value) # Not reachable. All possible type nodes have been considered. raise TypeError( # pragma: no cover f"Unexpected type node: '{inspect(type_node)}'." )
python
def type_from_ast(schema, type_node): # noqa: F811 if isinstance(type_node, ListTypeNode): inner_type = type_from_ast(schema, type_node.type) return GraphQLList(inner_type) if inner_type else None if isinstance(type_node, NonNullTypeNode): inner_type = type_from_ast(schema, type_node.type) return GraphQLNonNull(inner_type) if inner_type else None if isinstance(type_node, NamedTypeNode): return schema.get_type(type_node.name.value) # Not reachable. All possible type nodes have been considered. raise TypeError( # pragma: no cover f"Unexpected type node: '{inspect(type_node)}'." )
[ "def", "type_from_ast", "(", "schema", ",", "type_node", ")", ":", "# noqa: F811", "if", "isinstance", "(", "type_node", ",", "ListTypeNode", ")", ":", "inner_type", "=", "type_from_ast", "(", "schema", ",", "type_node", ".", "type", ")", "return", "GraphQLLis...
Get the GraphQL type definition from an AST node. Given a Schema and an AST node describing a type, return a GraphQLType definition which applies to that type. For example, if provided the parsed AST node for `[User]`, a GraphQLList instance will be returned, containing the type called "User" found in the schema. If a type called "User" is not found in the schema, then None will be returned.
[ "Get", "the", "GraphQL", "type", "definition", "from", "an", "AST", "node", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/type_from_ast.py#L42-L63
226,159
graphql-python/graphql-core-next
graphql/validation/rules/fields_on_correct_type.py
get_suggested_type_names
def get_suggested_type_names( schema: GraphQLSchema, type_: GraphQLOutputType, field_name: str ) -> List[str]: """ Get a list of suggested type names. Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces. """ if is_abstract_type(type_): type_ = cast(GraphQLAbstractType, type_) suggested_object_types = [] interface_usage_count: Dict[str, int] = defaultdict(int) for possible_type in schema.get_possible_types(type_): if field_name not in possible_type.fields: continue # This object type defines this field. suggested_object_types.append(possible_type.name) for possible_interface in possible_type.interfaces: if field_name not in possible_interface.fields: continue # This interface type defines this field. interface_usage_count[possible_interface.name] += 1 # Suggest interface types based on how common they are. suggested_interface_types = sorted( interface_usage_count, key=lambda k: -interface_usage_count[k] ) # Suggest both interface and object types. return suggested_interface_types + suggested_object_types # Otherwise, must be an Object type, which does not have possible fields. return []
python
def get_suggested_type_names( schema: GraphQLSchema, type_: GraphQLOutputType, field_name: str ) -> List[str]: if is_abstract_type(type_): type_ = cast(GraphQLAbstractType, type_) suggested_object_types = [] interface_usage_count: Dict[str, int] = defaultdict(int) for possible_type in schema.get_possible_types(type_): if field_name not in possible_type.fields: continue # This object type defines this field. suggested_object_types.append(possible_type.name) for possible_interface in possible_type.interfaces: if field_name not in possible_interface.fields: continue # This interface type defines this field. interface_usage_count[possible_interface.name] += 1 # Suggest interface types based on how common they are. suggested_interface_types = sorted( interface_usage_count, key=lambda k: -interface_usage_count[k] ) # Suggest both interface and object types. return suggested_interface_types + suggested_object_types # Otherwise, must be an Object type, which does not have possible fields. return []
[ "def", "get_suggested_type_names", "(", "schema", ":", "GraphQLSchema", ",", "type_", ":", "GraphQLOutputType", ",", "field_name", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "is_abstract_type", "(", "type_", ")", ":", "type_", "=", "cast", ...
Get a list of suggested type names. Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.
[ "Get", "a", "list", "of", "suggested", "type", "names", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/fields_on_correct_type.py#L71-L106
226,160
graphql-python/graphql-core-next
graphql/validation/rules/fields_on_correct_type.py
get_suggested_field_names
def get_suggested_field_names(type_: GraphQLOutputType, field_name: str) -> List[str]: """Get a list of suggested field names. For the field name provided, determine if there are any similar field names that may be the result of a typo. """ if is_object_type(type_) or is_interface_type(type_): possible_field_names = list(type_.fields) # type: ignore return suggestion_list(field_name, possible_field_names) # Otherwise, must be a Union type, which does not define fields. return []
python
def get_suggested_field_names(type_: GraphQLOutputType, field_name: str) -> List[str]: if is_object_type(type_) or is_interface_type(type_): possible_field_names = list(type_.fields) # type: ignore return suggestion_list(field_name, possible_field_names) # Otherwise, must be a Union type, which does not define fields. return []
[ "def", "get_suggested_field_names", "(", "type_", ":", "GraphQLOutputType", ",", "field_name", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "is_object_type", "(", "type_", ")", "or", "is_interface_type", "(", "type_", ")", ":", "possible_field_na...
Get a list of suggested field names. For the field name provided, determine if there are any similar field names that may be the result of a typo.
[ "Get", "a", "list", "of", "suggested", "field", "names", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/fields_on_correct_type.py#L109-L119
226,161
graphql-python/graphql-core-next
graphql/language/parser.py
parse
def parse( source: SourceType, no_location=False, experimental_fragment_variables=False ) -> DocumentNode: """Given a GraphQL source, parse it into a Document. Throws GraphQLError if a syntax error is encountered. By default, the parser creates AST nodes that know the location in the source that they correspond to. The `no_location` option disables that behavior for performance or testing. Experimental features: If `experimental_fragment_variables` is set to True, the parser will understand and parse variable definitions contained in a fragment definition. They'll be represented in the `variable_definitions` field of the `FragmentDefinitionNode`. The syntax is identical to normal, query-defined variables. For example:: fragment A($var: Boolean = false) on T { ... } """ if isinstance(source, str): source = Source(source) elif not isinstance(source, Source): raise TypeError(f"Must provide Source. Received: {inspect(source)}") lexer = Lexer( source, no_location=no_location, experimental_fragment_variables=experimental_fragment_variables, ) return parse_document(lexer)
python
def parse( source: SourceType, no_location=False, experimental_fragment_variables=False ) -> DocumentNode: if isinstance(source, str): source = Source(source) elif not isinstance(source, Source): raise TypeError(f"Must provide Source. Received: {inspect(source)}") lexer = Lexer( source, no_location=no_location, experimental_fragment_variables=experimental_fragment_variables, ) return parse_document(lexer)
[ "def", "parse", "(", "source", ":", "SourceType", ",", "no_location", "=", "False", ",", "experimental_fragment_variables", "=", "False", ")", "->", "DocumentNode", ":", "if", "isinstance", "(", "source", ",", "str", ")", ":", "source", "=", "Source", "(", ...
Given a GraphQL source, parse it into a Document. Throws GraphQLError if a syntax error is encountered. By default, the parser creates AST nodes that know the location in the source that they correspond to. The `no_location` option disables that behavior for performance or testing. Experimental features: If `experimental_fragment_variables` is set to True, the parser will understand and parse variable definitions contained in a fragment definition. They'll be represented in the `variable_definitions` field of the `FragmentDefinitionNode`. The syntax is identical to normal, query-defined variables. For example:: fragment A($var: Boolean = false) on T { ... }
[ "Given", "a", "GraphQL", "source", "parse", "it", "into", "a", "Document", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L70-L102
226,162
graphql-python/graphql-core-next
graphql/language/parser.py
parse_value
def parse_value(source: SourceType, **options: dict) -> ValueNode: """Parse the AST for a given string containing a GraphQL value. Throws GraphQLError if a syntax error is encountered. This is useful within tools that operate upon GraphQL Values directly and in isolation of complete GraphQL documents. Consider providing the results to the utility function: `value_from_ast()`. """ if isinstance(source, str): source = Source(source) lexer = Lexer(source, **options) expect_token(lexer, TokenKind.SOF) value = parse_value_literal(lexer, False) expect_token(lexer, TokenKind.EOF) return value
python
def parse_value(source: SourceType, **options: dict) -> ValueNode: if isinstance(source, str): source = Source(source) lexer = Lexer(source, **options) expect_token(lexer, TokenKind.SOF) value = parse_value_literal(lexer, False) expect_token(lexer, TokenKind.EOF) return value
[ "def", "parse_value", "(", "source", ":", "SourceType", ",", "*", "*", "options", ":", "dict", ")", "->", "ValueNode", ":", "if", "isinstance", "(", "source", ",", "str", ")", ":", "source", "=", "Source", "(", "source", ")", "lexer", "=", "Lexer", "...
Parse the AST for a given string containing a GraphQL value. Throws GraphQLError if a syntax error is encountered. This is useful within tools that operate upon GraphQL Values directly and in isolation of complete GraphQL documents. Consider providing the results to the utility function: `value_from_ast()`.
[ "Parse", "the", "AST", "for", "a", "given", "string", "containing", "a", "GraphQL", "value", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L105-L121
226,163
graphql-python/graphql-core-next
graphql/language/parser.py
parse_type
def parse_type(source: SourceType, **options: dict) -> TypeNode: """Parse the AST for a given string containing a GraphQL Type. Throws GraphQLError if a syntax error is encountered. This is useful within tools that operate upon GraphQL Types directly and in isolation of complete GraphQL documents. Consider providing the results to the utility function: `type_from_ast()`. """ if isinstance(source, str): source = Source(source) lexer = Lexer(source, **options) expect_token(lexer, TokenKind.SOF) type_ = parse_type_reference(lexer) expect_token(lexer, TokenKind.EOF) return type_
python
def parse_type(source: SourceType, **options: dict) -> TypeNode: if isinstance(source, str): source = Source(source) lexer = Lexer(source, **options) expect_token(lexer, TokenKind.SOF) type_ = parse_type_reference(lexer) expect_token(lexer, TokenKind.EOF) return type_
[ "def", "parse_type", "(", "source", ":", "SourceType", ",", "*", "*", "options", ":", "dict", ")", "->", "TypeNode", ":", "if", "isinstance", "(", "source", ",", "str", ")", ":", "source", "=", "Source", "(", "source", ")", "lexer", "=", "Lexer", "("...
Parse the AST for a given string containing a GraphQL Type. Throws GraphQLError if a syntax error is encountered. This is useful within tools that operate upon GraphQL Types directly and in isolation of complete GraphQL documents. Consider providing the results to the utility function: `type_from_ast()`.
[ "Parse", "the", "AST", "for", "a", "given", "string", "containing", "a", "GraphQL", "Type", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L124-L140
226,164
graphql-python/graphql-core-next
graphql/language/parser.py
parse_name
def parse_name(lexer: Lexer) -> NameNode: """Convert a name lex token into a name parse node.""" token = expect_token(lexer, TokenKind.NAME) return NameNode(value=token.value, loc=loc(lexer, token))
python
def parse_name(lexer: Lexer) -> NameNode: token = expect_token(lexer, TokenKind.NAME) return NameNode(value=token.value, loc=loc(lexer, token))
[ "def", "parse_name", "(", "lexer", ":", "Lexer", ")", "->", "NameNode", ":", "token", "=", "expect_token", "(", "lexer", ",", "TokenKind", ".", "NAME", ")", "return", "NameNode", "(", "value", "=", "token", ".", "value", ",", "loc", "=", "loc", "(", ...
Convert a name lex token into a name parse node.
[ "Convert", "a", "name", "lex", "token", "into", "a", "name", "parse", "node", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L143-L146
226,165
graphql-python/graphql-core-next
graphql/language/parser.py
parse_fragment
def parse_fragment(lexer: Lexer) -> Union[FragmentSpreadNode, InlineFragmentNode]: """Corresponds to both FragmentSpread and InlineFragment in the spec. FragmentSpread: ... FragmentName Directives? InlineFragment: ... TypeCondition? Directives? SelectionSet """ start = lexer.token expect_token(lexer, TokenKind.SPREAD) has_type_condition = expect_optional_keyword(lexer, "on") if not has_type_condition and peek(lexer, TokenKind.NAME): return FragmentSpreadNode( name=parse_fragment_name(lexer), directives=parse_directives(lexer, False), loc=loc(lexer, start), ) return InlineFragmentNode( type_condition=parse_named_type(lexer) if has_type_condition else None, directives=parse_directives(lexer, False), selection_set=parse_selection_set(lexer), loc=loc(lexer, start), )
python
def parse_fragment(lexer: Lexer) -> Union[FragmentSpreadNode, InlineFragmentNode]: start = lexer.token expect_token(lexer, TokenKind.SPREAD) has_type_condition = expect_optional_keyword(lexer, "on") if not has_type_condition and peek(lexer, TokenKind.NAME): return FragmentSpreadNode( name=parse_fragment_name(lexer), directives=parse_directives(lexer, False), loc=loc(lexer, start), ) return InlineFragmentNode( type_condition=parse_named_type(lexer) if has_type_condition else None, directives=parse_directives(lexer, False), selection_set=parse_selection_set(lexer), loc=loc(lexer, start), )
[ "def", "parse_fragment", "(", "lexer", ":", "Lexer", ")", "->", "Union", "[", "FragmentSpreadNode", ",", "InlineFragmentNode", "]", ":", "start", "=", "lexer", ".", "token", "expect_token", "(", "lexer", ",", "TokenKind", ".", "SPREAD", ")", "has_type_conditio...
Corresponds to both FragmentSpread and InlineFragment in the spec. FragmentSpread: ... FragmentName Directives? InlineFragment: ... TypeCondition? Directives? SelectionSet
[ "Corresponds", "to", "both", "FragmentSpread", "and", "InlineFragment", "in", "the", "spec", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L331-L352
226,166
graphql-python/graphql-core-next
graphql/language/parser.py
loc
def loc(lexer: Lexer, start_token: Token) -> Optional[Location]: """Return a location object. Used to identify the place in the source that created a given parsed object. """ if not lexer.no_location: end_token = lexer.last_token source = lexer.source return Location( start_token.start, end_token.end, start_token, end_token, source ) return None
python
def loc(lexer: Lexer, start_token: Token) -> Optional[Location]: if not lexer.no_location: end_token = lexer.last_token source = lexer.source return Location( start_token.start, end_token.end, start_token, end_token, source ) return None
[ "def", "loc", "(", "lexer", ":", "Lexer", ",", "start_token", ":", "Token", ")", "->", "Optional", "[", "Location", "]", ":", "if", "not", "lexer", ".", "no_location", ":", "end_token", "=", "lexer", ".", "last_token", "source", "=", "lexer", ".", "sou...
Return a location object. Used to identify the place in the source that created a given parsed object.
[ "Return", "a", "location", "object", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1042-L1053
226,167
graphql-python/graphql-core-next
graphql/language/parser.py
expect_token
def expect_token(lexer: Lexer, kind: TokenKind) -> Token: """Expect the next token to be of the given kind. If the next token is of the given kind, return that token after advancing the lexer. Otherwise, do not change the parser state and throw an error. """ token = lexer.token if token.kind == kind: lexer.advance() return token raise GraphQLSyntaxError( lexer.source, token.start, f"Expected {kind.value}, found {token.kind.value}" )
python
def expect_token(lexer: Lexer, kind: TokenKind) -> Token: token = lexer.token if token.kind == kind: lexer.advance() return token raise GraphQLSyntaxError( lexer.source, token.start, f"Expected {kind.value}, found {token.kind.value}" )
[ "def", "expect_token", "(", "lexer", ":", "Lexer", ",", "kind", ":", "TokenKind", ")", "->", "Token", ":", "token", "=", "lexer", ".", "token", "if", "token", ".", "kind", "==", "kind", ":", "lexer", ".", "advance", "(", ")", "return", "token", "rais...
Expect the next token to be of the given kind. If the next token is of the given kind, return that token after advancing the lexer. Otherwise, do not change the parser state and throw an error.
[ "Expect", "the", "next", "token", "to", "be", "of", "the", "given", "kind", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1061-L1074
226,168
graphql-python/graphql-core-next
graphql/language/parser.py
expect_optional_token
def expect_optional_token(lexer: Lexer, kind: TokenKind) -> Optional[Token]: """Expect the next token optionally to be of the given kind. If the next token is of the given kind, return that token after advancing the lexer. Otherwise, do not change the parser state and return None. """ token = lexer.token if token.kind == kind: lexer.advance() return token return None
python
def expect_optional_token(lexer: Lexer, kind: TokenKind) -> Optional[Token]: token = lexer.token if token.kind == kind: lexer.advance() return token return None
[ "def", "expect_optional_token", "(", "lexer", ":", "Lexer", ",", "kind", ":", "TokenKind", ")", "->", "Optional", "[", "Token", "]", ":", "token", "=", "lexer", ".", "token", "if", "token", ".", "kind", "==", "kind", ":", "lexer", ".", "advance", "(", ...
Expect the next token optionally to be of the given kind. If the next token is of the given kind, return that token after advancing the lexer. Otherwise, do not change the parser state and return None.
[ "Expect", "the", "next", "token", "optionally", "to", "be", "of", "the", "given", "kind", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1077-L1088
226,169
graphql-python/graphql-core-next
graphql/language/parser.py
expect_keyword
def expect_keyword(lexer: Lexer, value: str) -> Token: """Expect the next token to be a given keyword. If the next token is a given keyword, return that token after advancing the lexer. Otherwise, do not change the parser state and throw an error. """ token = lexer.token if token.kind == TokenKind.NAME and token.value == value: lexer.advance() return token raise GraphQLSyntaxError( lexer.source, token.start, f"Expected {value!r}, found {token.desc}" )
python
def expect_keyword(lexer: Lexer, value: str) -> Token: token = lexer.token if token.kind == TokenKind.NAME and token.value == value: lexer.advance() return token raise GraphQLSyntaxError( lexer.source, token.start, f"Expected {value!r}, found {token.desc}" )
[ "def", "expect_keyword", "(", "lexer", ":", "Lexer", ",", "value", ":", "str", ")", "->", "Token", ":", "token", "=", "lexer", ".", "token", "if", "token", ".", "kind", "==", "TokenKind", ".", "NAME", "and", "token", ".", "value", "==", "value", ":",...
Expect the next token to be a given keyword. If the next token is a given keyword, return that token after advancing the lexer. Otherwise, do not change the parser state and throw an error.
[ "Expect", "the", "next", "token", "to", "be", "a", "given", "keyword", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1091-L1104
226,170
graphql-python/graphql-core-next
graphql/language/parser.py
expect_optional_keyword
def expect_optional_keyword(lexer: Lexer, value: str) -> Optional[Token]: """Expect the next token optionally to be a given keyword. If the next token is a given keyword, return that token after advancing the lexer. Otherwise, do not change the parser state and return None. """ token = lexer.token if token.kind == TokenKind.NAME and token.value == value: lexer.advance() return token return None
python
def expect_optional_keyword(lexer: Lexer, value: str) -> Optional[Token]: token = lexer.token if token.kind == TokenKind.NAME and token.value == value: lexer.advance() return token return None
[ "def", "expect_optional_keyword", "(", "lexer", ":", "Lexer", ",", "value", ":", "str", ")", "->", "Optional", "[", "Token", "]", ":", "token", "=", "lexer", ".", "token", "if", "token", ".", "kind", "==", "TokenKind", ".", "NAME", "and", "token", ".",...
Expect the next token optionally to be a given keyword. If the next token is a given keyword, return that token after advancing the lexer. Otherwise, do not change the parser state and return None.
[ "Expect", "the", "next", "token", "optionally", "to", "be", "a", "given", "keyword", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1107-L1118
226,171
graphql-python/graphql-core-next
graphql/language/parser.py
unexpected
def unexpected(lexer: Lexer, at_token: Token = None) -> GraphQLError: """Create an error when an unexpected lexed token is encountered.""" token = at_token or lexer.token return GraphQLSyntaxError(lexer.source, token.start, f"Unexpected {token.desc}")
python
def unexpected(lexer: Lexer, at_token: Token = None) -> GraphQLError: token = at_token or lexer.token return GraphQLSyntaxError(lexer.source, token.start, f"Unexpected {token.desc}")
[ "def", "unexpected", "(", "lexer", ":", "Lexer", ",", "at_token", ":", "Token", "=", "None", ")", "->", "GraphQLError", ":", "token", "=", "at_token", "or", "lexer", ".", "token", "return", "GraphQLSyntaxError", "(", "lexer", ".", "source", ",", "token", ...
Create an error when an unexpected lexed token is encountered.
[ "Create", "an", "error", "when", "an", "unexpected", "lexed", "token", "is", "encountered", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1121-L1124
226,172
graphql-python/graphql-core-next
graphql/language/parser.py
many_nodes
def many_nodes( lexer: Lexer, open_kind: TokenKind, parse_fn: Callable[[Lexer], Node], close_kind: TokenKind, ) -> List[Node]: """Fetch matching nodes, at least one. Returns a non-empty list of parse nodes, determined by the `parse_fn`. This list begins with a lex token of `open_kind` and ends with a lex token of `close_kind`. Advances the parser to the next lex token after the closing token. """ expect_token(lexer, open_kind) nodes = [parse_fn(lexer)] append = nodes.append while not expect_optional_token(lexer, close_kind): append(parse_fn(lexer)) return nodes
python
def many_nodes( lexer: Lexer, open_kind: TokenKind, parse_fn: Callable[[Lexer], Node], close_kind: TokenKind, ) -> List[Node]: expect_token(lexer, open_kind) nodes = [parse_fn(lexer)] append = nodes.append while not expect_optional_token(lexer, close_kind): append(parse_fn(lexer)) return nodes
[ "def", "many_nodes", "(", "lexer", ":", "Lexer", ",", "open_kind", ":", "TokenKind", ",", "parse_fn", ":", "Callable", "[", "[", "Lexer", "]", ",", "Node", "]", ",", "close_kind", ":", "TokenKind", ",", ")", "->", "List", "[", "Node", "]", ":", "expe...
Fetch matching nodes, at least one. Returns a non-empty list of parse nodes, determined by the `parse_fn`. This list begins with a lex token of `open_kind` and ends with a lex token of `close_kind`. Advances the parser to the next lex token after the closing token.
[ "Fetch", "matching", "nodes", "at", "least", "one", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L1147-L1164
226,173
graphql-python/graphql-core-next
graphql/utilities/coerce_value.py
coercion_error
def coercion_error( message: str, blame_node: Node = None, path: Path = None, sub_message: str = None, original_error: Exception = None, ) -> GraphQLError: """Return a GraphQLError instance""" if path: path_str = print_path(path) message += f" at {path_str}" message += f"; {sub_message}" if sub_message else "." # noinspection PyArgumentEqualDefault return GraphQLError(message, blame_node, None, None, None, original_error)
python
def coercion_error( message: str, blame_node: Node = None, path: Path = None, sub_message: str = None, original_error: Exception = None, ) -> GraphQLError: if path: path_str = print_path(path) message += f" at {path_str}" message += f"; {sub_message}" if sub_message else "." # noinspection PyArgumentEqualDefault return GraphQLError(message, blame_node, None, None, None, original_error)
[ "def", "coercion_error", "(", "message", ":", "str", ",", "blame_node", ":", "Node", "=", "None", ",", "path", ":", "Path", "=", "None", ",", "sub_message", ":", "str", "=", "None", ",", "original_error", ":", "Exception", "=", "None", ",", ")", "->", ...
Return a GraphQLError instance
[ "Return", "a", "GraphQLError", "instance" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/coerce_value.py#L200-L213
226,174
graphql-python/graphql-core-next
graphql/utilities/coerce_value.py
print_path
def print_path(path: Path) -> str: """Build string describing the path into the value where error was found""" path_str = "" current_path: Optional[Path] = path while current_path: path_str = ( f".{current_path.key}" if isinstance(current_path.key, str) else f"[{current_path.key}]" ) + path_str current_path = current_path.prev return f"value{path_str}" if path_str else ""
python
def print_path(path: Path) -> str: path_str = "" current_path: Optional[Path] = path while current_path: path_str = ( f".{current_path.key}" if isinstance(current_path.key, str) else f"[{current_path.key}]" ) + path_str current_path = current_path.prev return f"value{path_str}" if path_str else ""
[ "def", "print_path", "(", "path", ":", "Path", ")", "->", "str", ":", "path_str", "=", "\"\"", "current_path", ":", "Optional", "[", "Path", "]", "=", "path", "while", "current_path", ":", "path_str", "=", "(", "f\".{current_path.key}\"", "if", "isinstance",...
Build string describing the path into the value where error was found
[ "Build", "string", "describing", "the", "path", "into", "the", "value", "where", "error", "was", "found" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/coerce_value.py#L216-L227
226,175
graphql-python/graphql-core-next
graphql/type/scalars.py
parse_int_literal
def parse_int_literal(ast, _variables=None): """Parse an integer value node in the AST.""" if isinstance(ast, IntValueNode): num = int(ast.value) if MIN_INT <= num <= MAX_INT: return num return INVALID
python
def parse_int_literal(ast, _variables=None): if isinstance(ast, IntValueNode): num = int(ast.value) if MIN_INT <= num <= MAX_INT: return num return INVALID
[ "def", "parse_int_literal", "(", "ast", ",", "_variables", "=", "None", ")", ":", "if", "isinstance", "(", "ast", ",", "IntValueNode", ")", ":", "num", "=", "int", "(", "ast", ".", "value", ")", "if", "MIN_INT", "<=", "num", "<=", "MAX_INT", ":", "re...
Parse an integer value node in the AST.
[ "Parse", "an", "integer", "value", "node", "in", "the", "AST", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/scalars.py#L72-L78
226,176
graphql-python/graphql-core-next
graphql/type/scalars.py
parse_float_literal
def parse_float_literal(ast, _variables=None): """Parse a float value node in the AST.""" if isinstance(ast, (FloatValueNode, IntValueNode)): return float(ast.value) return INVALID
python
def parse_float_literal(ast, _variables=None): if isinstance(ast, (FloatValueNode, IntValueNode)): return float(ast.value) return INVALID
[ "def", "parse_float_literal", "(", "ast", ",", "_variables", "=", "None", ")", ":", "if", "isinstance", "(", "ast", ",", "(", "FloatValueNode", ",", "IntValueNode", ")", ")", ":", "return", "float", "(", "ast", ".", "value", ")", "return", "INVALID" ]
Parse a float value node in the AST.
[ "Parse", "a", "float", "value", "node", "in", "the", "AST", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/scalars.py#L113-L117
226,177
graphql-python/graphql-core-next
graphql/type/scalars.py
parse_id_literal
def parse_id_literal(ast, _variables=None): """Parse an ID value node in the AST.""" if isinstance(ast, (StringValueNode, IntValueNode)): return ast.value return INVALID
python
def parse_id_literal(ast, _variables=None): if isinstance(ast, (StringValueNode, IntValueNode)): return ast.value return INVALID
[ "def", "parse_id_literal", "(", "ast", ",", "_variables", "=", "None", ")", ":", "if", "isinstance", "(", "ast", ",", "(", "StringValueNode", ",", "IntValueNode", ")", ")", ":", "return", "ast", ".", "value", "return", "INVALID" ]
Parse an ID value node in the AST.
[ "Parse", "an", "ID", "value", "node", "in", "the", "AST", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/scalars.py#L223-L227
226,178
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_breaking_changes
def find_breaking_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: """Find breaking changes. Given two schemas, returns a list containing descriptions of all the types of breaking changes covered by the other functions down below. """ return ( find_removed_types(old_schema, new_schema) + find_types_that_changed_kind(old_schema, new_schema) + find_fields_that_changed_type_on_object_or_interface_types( old_schema, new_schema ) + find_fields_that_changed_type_on_input_object_types( old_schema, new_schema ).breaking_changes + find_types_removed_from_unions(old_schema, new_schema) + find_values_removed_from_enums(old_schema, new_schema) + find_arg_changes(old_schema, new_schema).breaking_changes + find_interfaces_removed_from_object_types(old_schema, new_schema) + find_removed_directives(old_schema, new_schema) + find_removed_directive_args(old_schema, new_schema) + find_added_non_null_directive_args(old_schema, new_schema) + find_removed_directive_locations(old_schema, new_schema) )
python
def find_breaking_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: return ( find_removed_types(old_schema, new_schema) + find_types_that_changed_kind(old_schema, new_schema) + find_fields_that_changed_type_on_object_or_interface_types( old_schema, new_schema ) + find_fields_that_changed_type_on_input_object_types( old_schema, new_schema ).breaking_changes + find_types_removed_from_unions(old_schema, new_schema) + find_values_removed_from_enums(old_schema, new_schema) + find_arg_changes(old_schema, new_schema).breaking_changes + find_interfaces_removed_from_object_types(old_schema, new_schema) + find_removed_directives(old_schema, new_schema) + find_removed_directive_args(old_schema, new_schema) + find_added_non_null_directive_args(old_schema, new_schema) + find_removed_directive_locations(old_schema, new_schema) )
[ "def", "find_breaking_changes", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "BreakingChange", "]", ":", "return", "(", "find_removed_types", "(", "old_schema", ",", "new_schema", ")", "+", "find_types_t...
Find breaking changes. Given two schemas, returns a list containing descriptions of all the types of breaking changes covered by the other functions down below.
[ "Find", "breaking", "changes", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L100-L125
226,179
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_dangerous_changes
def find_dangerous_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: """Find dangerous changes. Given two schemas, returns a list containing descriptions of all the types of potentially dangerous changes covered by the other functions down below. """ return ( find_arg_changes(old_schema, new_schema).dangerous_changes + find_values_added_to_enums(old_schema, new_schema) + find_interfaces_added_to_object_types(old_schema, new_schema) + find_types_added_to_unions(old_schema, new_schema) + find_fields_that_changed_type_on_input_object_types( old_schema, new_schema ).dangerous_changes )
python
def find_dangerous_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: return ( find_arg_changes(old_schema, new_schema).dangerous_changes + find_values_added_to_enums(old_schema, new_schema) + find_interfaces_added_to_object_types(old_schema, new_schema) + find_types_added_to_unions(old_schema, new_schema) + find_fields_that_changed_type_on_input_object_types( old_schema, new_schema ).dangerous_changes )
[ "def", "find_dangerous_changes", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "DangerousChange", "]", ":", "return", "(", "find_arg_changes", "(", "old_schema", ",", "new_schema", ")", ".", "dangerous_ch...
Find dangerous changes. Given two schemas, returns a list containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.
[ "Find", "dangerous", "changes", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L128-L144
226,180
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_removed_types
def find_removed_types( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: """Find removed types. Given two schemas, returns a list containing descriptions of any breaking changes in the newSchema related to removing an entire type. """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes = [] for type_name in old_type_map: if type_name not in new_type_map: breaking_changes.append( BreakingChange( BreakingChangeType.TYPE_REMOVED, f"{type_name} was removed." ) ) return breaking_changes
python
def find_removed_types( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes = [] for type_name in old_type_map: if type_name not in new_type_map: breaking_changes.append( BreakingChange( BreakingChangeType.TYPE_REMOVED, f"{type_name} was removed." ) ) return breaking_changes
[ "def", "find_removed_types", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "BreakingChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".", "type_map...
Find removed types. Given two schemas, returns a list containing descriptions of any breaking changes in the newSchema related to removing an entire type.
[ "Find", "removed", "types", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L147-L166
226,181
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_types_that_changed_kind
def find_types_that_changed_kind( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: """Find types that changed kind Given two schemas, returns a list containing descriptions of any breaking changes in the newSchema related to changing the type of a type. """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes = [] for type_name in old_type_map: if type_name not in new_type_map: continue old_type = old_type_map[type_name] new_type = new_type_map[type_name] if old_type.__class__ is not new_type.__class__: breaking_changes.append( BreakingChange( BreakingChangeType.TYPE_CHANGED_KIND, f"{type_name} changed from {type_kind_name(old_type)}" f" to {type_kind_name(new_type)}.", ) ) return breaking_changes
python
def find_types_that_changed_kind( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes = [] for type_name in old_type_map: if type_name not in new_type_map: continue old_type = old_type_map[type_name] new_type = new_type_map[type_name] if old_type.__class__ is not new_type.__class__: breaking_changes.append( BreakingChange( BreakingChangeType.TYPE_CHANGED_KIND, f"{type_name} changed from {type_kind_name(old_type)}" f" to {type_kind_name(new_type)}.", ) ) return breaking_changes
[ "def", "find_types_that_changed_kind", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "BreakingChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".", ...
Find types that changed kind Given two schemas, returns a list containing descriptions of any breaking changes in the newSchema related to changing the type of a type.
[ "Find", "types", "that", "changed", "kind" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L169-L194
226,182
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_arg_changes
def find_arg_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> BreakingAndDangerousChanges: """Find argument changes. Given two schemas, returns a list containing descriptions of any breaking or dangerous changes in the new_schema related to arguments (such as removal or change of type of an argument, or a change in an argument's default value). """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes: List[BreakingChange] = [] dangerous_changes: List[DangerousChange] = [] for type_name, old_type in old_type_map.items(): new_type = new_type_map.get(type_name) if ( not (is_object_type(old_type) or is_interface_type(old_type)) or not (is_object_type(new_type) or is_interface_type(new_type)) or new_type.__class__ is not old_type.__class__ ): continue old_type = cast(Union[GraphQLObjectType, GraphQLInterfaceType], old_type) new_type = cast(Union[GraphQLObjectType, GraphQLInterfaceType], new_type) old_type_fields = old_type.fields new_type_fields = new_type.fields for field_name in old_type_fields: if field_name not in new_type_fields: continue old_args = old_type_fields[field_name].args new_args = new_type_fields[field_name].args for arg_name, old_arg in old_args.items(): new_arg = new_args.get(arg_name) if not new_arg: # Arg not present breaking_changes.append( BreakingChange( BreakingChangeType.ARG_REMOVED, f"{old_type.name}.{field_name} arg" f" {arg_name} was removed", ) ) continue is_safe = is_change_safe_for_input_object_field_or_field_arg( old_arg.type, new_arg.type ) if not is_safe: breaking_changes.append( BreakingChange( BreakingChangeType.ARG_CHANGED_KIND, f"{old_type.name}.{field_name} arg" f" {arg_name} has changed type from" f" {old_arg.type} to {new_arg.type}", ) ) elif ( old_arg.default_value is not INVALID and old_arg.default_value != new_arg.default_value ): dangerous_changes.append( DangerousChange( DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, f"{old_type.name}.{field_name} arg" f" {arg_name} has changed defaultValue", ) ) # Check if arg was added to the field for arg_name in new_args: if arg_name not in old_args: new_arg_def = new_args[arg_name] if is_required_argument(new_arg_def): breaking_changes.append( BreakingChange( BreakingChangeType.REQUIRED_ARG_ADDED, f"A required arg {arg_name} on" f" {type_name}.{field_name} was added", ) ) else: dangerous_changes.append( DangerousChange( DangerousChangeType.OPTIONAL_ARG_ADDED, f"An optional arg {arg_name} on" f" {type_name}.{field_name} was added", ) ) return BreakingAndDangerousChanges(breaking_changes, dangerous_changes)
python
def find_arg_changes( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> BreakingAndDangerousChanges: old_type_map = old_schema.type_map new_type_map = new_schema.type_map breaking_changes: List[BreakingChange] = [] dangerous_changes: List[DangerousChange] = [] for type_name, old_type in old_type_map.items(): new_type = new_type_map.get(type_name) if ( not (is_object_type(old_type) or is_interface_type(old_type)) or not (is_object_type(new_type) or is_interface_type(new_type)) or new_type.__class__ is not old_type.__class__ ): continue old_type = cast(Union[GraphQLObjectType, GraphQLInterfaceType], old_type) new_type = cast(Union[GraphQLObjectType, GraphQLInterfaceType], new_type) old_type_fields = old_type.fields new_type_fields = new_type.fields for field_name in old_type_fields: if field_name not in new_type_fields: continue old_args = old_type_fields[field_name].args new_args = new_type_fields[field_name].args for arg_name, old_arg in old_args.items(): new_arg = new_args.get(arg_name) if not new_arg: # Arg not present breaking_changes.append( BreakingChange( BreakingChangeType.ARG_REMOVED, f"{old_type.name}.{field_name} arg" f" {arg_name} was removed", ) ) continue is_safe = is_change_safe_for_input_object_field_or_field_arg( old_arg.type, new_arg.type ) if not is_safe: breaking_changes.append( BreakingChange( BreakingChangeType.ARG_CHANGED_KIND, f"{old_type.name}.{field_name} arg" f" {arg_name} has changed type from" f" {old_arg.type} to {new_arg.type}", ) ) elif ( old_arg.default_value is not INVALID and old_arg.default_value != new_arg.default_value ): dangerous_changes.append( DangerousChange( DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, f"{old_type.name}.{field_name} arg" f" {arg_name} has changed defaultValue", ) ) # Check if arg was added to the field for arg_name in new_args: if arg_name not in old_args: new_arg_def = new_args[arg_name] if is_required_argument(new_arg_def): breaking_changes.append( BreakingChange( BreakingChangeType.REQUIRED_ARG_ADDED, f"A required arg {arg_name} on" f" {type_name}.{field_name} was added", ) ) else: dangerous_changes.append( DangerousChange( DangerousChangeType.OPTIONAL_ARG_ADDED, f"An optional arg {arg_name} on" f" {type_name}.{field_name} was added", ) ) return BreakingAndDangerousChanges(breaking_changes, dangerous_changes)
[ "def", "find_arg_changes", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "BreakingAndDangerousChanges", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".", "type_map", "breakin...
Find argument changes. Given two schemas, returns a list containing descriptions of any breaking or dangerous changes in the new_schema related to arguments (such as removal or change of type of an argument, or a change in an argument's default value).
[ "Find", "argument", "changes", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L197-L288
226,183
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_types_removed_from_unions
def find_types_removed_from_unions( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: """Find types removed from unions. Given two schemas, returns a list containing descriptions of any breaking changes in the new_schema related to removing types from a union type. """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map types_removed_from_union = [] for old_type_name, old_type in old_type_map.items(): new_type = new_type_map.get(old_type_name) if not (is_union_type(old_type) and is_union_type(new_type)): continue old_type = cast(GraphQLUnionType, old_type) new_type = cast(GraphQLUnionType, new_type) type_names_in_new_union = {type_.name for type_ in new_type.types} for type_ in old_type.types: type_name = type_.name if type_name not in type_names_in_new_union: types_removed_from_union.append( BreakingChange( BreakingChangeType.TYPE_REMOVED_FROM_UNION, f"{type_name} was removed from union type {old_type_name}.", ) ) return types_removed_from_union
python
def find_types_removed_from_unions( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: old_type_map = old_schema.type_map new_type_map = new_schema.type_map types_removed_from_union = [] for old_type_name, old_type in old_type_map.items(): new_type = new_type_map.get(old_type_name) if not (is_union_type(old_type) and is_union_type(new_type)): continue old_type = cast(GraphQLUnionType, old_type) new_type = cast(GraphQLUnionType, new_type) type_names_in_new_union = {type_.name for type_ in new_type.types} for type_ in old_type.types: type_name = type_.name if type_name not in type_names_in_new_union: types_removed_from_union.append( BreakingChange( BreakingChangeType.TYPE_REMOVED_FROM_UNION, f"{type_name} was removed from union type {old_type_name}.", ) ) return types_removed_from_union
[ "def", "find_types_removed_from_unions", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "BreakingChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".",...
Find types removed from unions. Given two schemas, returns a list containing descriptions of any breaking changes in the new_schema related to removing types from a union type.
[ "Find", "types", "removed", "from", "unions", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L520-L548
226,184
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_types_added_to_unions
def find_types_added_to_unions( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: """Find types added to union. Given two schemas, returns a list containing descriptions of any dangerous changes in the new_schema related to adding types to a union type. """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map types_added_to_union = [] for new_type_name, new_type in new_type_map.items(): old_type = old_type_map.get(new_type_name) if not (is_union_type(old_type) and is_union_type(new_type)): continue old_type = cast(GraphQLUnionType, old_type) new_type = cast(GraphQLUnionType, new_type) type_names_in_old_union = {type_.name for type_ in old_type.types} for type_ in new_type.types: type_name = type_.name if type_name not in type_names_in_old_union: types_added_to_union.append( DangerousChange( DangerousChangeType.TYPE_ADDED_TO_UNION, f"{type_name} was added to union type {new_type_name}.", ) ) return types_added_to_union
python
def find_types_added_to_unions( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: old_type_map = old_schema.type_map new_type_map = new_schema.type_map types_added_to_union = [] for new_type_name, new_type in new_type_map.items(): old_type = old_type_map.get(new_type_name) if not (is_union_type(old_type) and is_union_type(new_type)): continue old_type = cast(GraphQLUnionType, old_type) new_type = cast(GraphQLUnionType, new_type) type_names_in_old_union = {type_.name for type_ in old_type.types} for type_ in new_type.types: type_name = type_.name if type_name not in type_names_in_old_union: types_added_to_union.append( DangerousChange( DangerousChangeType.TYPE_ADDED_TO_UNION, f"{type_name} was added to union type {new_type_name}.", ) ) return types_added_to_union
[ "def", "find_types_added_to_unions", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "DangerousChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".", ...
Find types added to union. Given two schemas, returns a list containing descriptions of any dangerous changes in the new_schema related to adding types to a union type.
[ "Find", "types", "added", "to", "union", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L551-L579
226,185
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_values_removed_from_enums
def find_values_removed_from_enums( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: """Find values removed from enums. Given two schemas, returns a list containing descriptions of any breaking changes in the new_schema related to removing values from an enum type. """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map values_removed_from_enums = [] for type_name, old_type in old_type_map.items(): new_type = new_type_map.get(type_name) if not (is_enum_type(old_type) and is_enum_type(new_type)): continue old_type = cast(GraphQLEnumType, old_type) new_type = cast(GraphQLEnumType, new_type) values_in_new_enum = new_type.values for value_name in old_type.values: if value_name not in values_in_new_enum: values_removed_from_enums.append( BreakingChange( BreakingChangeType.VALUE_REMOVED_FROM_ENUM, f"{value_name} was removed from enum type {type_name}.", ) ) return values_removed_from_enums
python
def find_values_removed_from_enums( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: old_type_map = old_schema.type_map new_type_map = new_schema.type_map values_removed_from_enums = [] for type_name, old_type in old_type_map.items(): new_type = new_type_map.get(type_name) if not (is_enum_type(old_type) and is_enum_type(new_type)): continue old_type = cast(GraphQLEnumType, old_type) new_type = cast(GraphQLEnumType, new_type) values_in_new_enum = new_type.values for value_name in old_type.values: if value_name not in values_in_new_enum: values_removed_from_enums.append( BreakingChange( BreakingChangeType.VALUE_REMOVED_FROM_ENUM, f"{value_name} was removed from enum type {type_name}.", ) ) return values_removed_from_enums
[ "def", "find_values_removed_from_enums", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "BreakingChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".",...
Find values removed from enums. Given two schemas, returns a list containing descriptions of any breaking changes in the new_schema related to removing values from an enum type.
[ "Find", "values", "removed", "from", "enums", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L582-L609
226,186
graphql-python/graphql-core-next
graphql/utilities/find_breaking_changes.py
find_values_added_to_enums
def find_values_added_to_enums( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: """Find values added to enums. Given two schemas, returns a list containing descriptions of any dangerous changes in the new_schema related to adding values to an enum type. """ old_type_map = old_schema.type_map new_type_map = new_schema.type_map values_added_to_enums = [] for type_name, old_type in old_type_map.items(): new_type = new_type_map.get(type_name) if not (is_enum_type(old_type) and is_enum_type(new_type)): continue old_type = cast(GraphQLEnumType, old_type) new_type = cast(GraphQLEnumType, new_type) values_in_old_enum = old_type.values for value_name in new_type.values: if value_name not in values_in_old_enum: values_added_to_enums.append( DangerousChange( DangerousChangeType.VALUE_ADDED_TO_ENUM, f"{value_name} was added to enum type {type_name}.", ) ) return values_added_to_enums
python
def find_values_added_to_enums( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[DangerousChange]: old_type_map = old_schema.type_map new_type_map = new_schema.type_map values_added_to_enums = [] for type_name, old_type in old_type_map.items(): new_type = new_type_map.get(type_name) if not (is_enum_type(old_type) and is_enum_type(new_type)): continue old_type = cast(GraphQLEnumType, old_type) new_type = cast(GraphQLEnumType, new_type) values_in_old_enum = old_type.values for value_name in new_type.values: if value_name not in values_in_old_enum: values_added_to_enums.append( DangerousChange( DangerousChangeType.VALUE_ADDED_TO_ENUM, f"{value_name} was added to enum type {type_name}.", ) ) return values_added_to_enums
[ "def", "find_values_added_to_enums", "(", "old_schema", ":", "GraphQLSchema", ",", "new_schema", ":", "GraphQLSchema", ")", "->", "List", "[", "DangerousChange", "]", ":", "old_type_map", "=", "old_schema", ".", "type_map", "new_type_map", "=", "new_schema", ".", ...
Find values added to enums. Given two schemas, returns a list containing descriptions of any dangerous changes in the new_schema related to adding values to an enum type.
[ "Find", "values", "added", "to", "enums", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_breaking_changes.py#L612-L639
226,187
graphql-python/graphql-core-next
graphql/pyutils/is_finite.py
is_finite
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
python
def is_finite(value: Any) -> bool: return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
[ "def", "is_finite", "(", "value", ":", "Any", ")", "->", "bool", ":", "return", "isinstance", "(", "value", ",", "int", ")", "or", "(", "isinstance", "(", "value", ",", "float", ")", "and", "isfinite", "(", "value", ")", ")" ]
Return true if a value is a finite number.
[ "Return", "true", "if", "a", "value", "is", "a", "finite", "number", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/is_finite.py#L7-L9
226,188
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
find_conflicts_within_selection_set
def find_conflicts_within_selection_set( context: ValidationContext, cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", parent_type: Optional[GraphQLNamedType], selection_set: SelectionSetNode, ) -> List[Conflict]: """Find conflicts within selection set. Find all conflicts found "within" a selection set, including those found via spreading in fragments. Called when visiting each SelectionSet in the GraphQL Document. """ conflicts: List[Conflict] = [] field_map, fragment_names = get_fields_and_fragment_names( context, cached_fields_and_fragment_names, parent_type, selection_set ) # (A) Find all conflicts "within" the fields of this selection set. # Note: this is the *only place* `collect_conflicts_within` is called. collect_conflicts_within( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, field_map, ) if fragment_names: compared_fragments: Set[str] = set() # (B) Then collect conflicts between these fields and those represented by each # spread fragment name found. for i, fragment_name in enumerate(fragment_names): collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, False, field_map, fragment_name, ) # (C) Then compare this fragment with all other fragments found in this # selection set to collect conflicts within fragments spread together. # This compares each item in the list of fragment names to every other # item in that same list (except for itself). for other_fragment_name in fragment_names[i + 1 :]: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, False, fragment_name, other_fragment_name, ) return conflicts
python
def find_conflicts_within_selection_set( context: ValidationContext, cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", parent_type: Optional[GraphQLNamedType], selection_set: SelectionSetNode, ) -> List[Conflict]: conflicts: List[Conflict] = [] field_map, fragment_names = get_fields_and_fragment_names( context, cached_fields_and_fragment_names, parent_type, selection_set ) # (A) Find all conflicts "within" the fields of this selection set. # Note: this is the *only place* `collect_conflicts_within` is called. collect_conflicts_within( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, field_map, ) if fragment_names: compared_fragments: Set[str] = set() # (B) Then collect conflicts between these fields and those represented by each # spread fragment name found. for i, fragment_name in enumerate(fragment_names): collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, False, field_map, fragment_name, ) # (C) Then compare this fragment with all other fragments found in this # selection set to collect conflicts within fragments spread together. # This compares each item in the list of fragment names to every other # item in that same list (except for itself). for other_fragment_name in fragment_names[i + 1 :]: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, False, fragment_name, other_fragment_name, ) return conflicts
[ "def", "find_conflicts_within_selection_set", "(", "context", ":", "ValidationContext", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "compared_fragment_pairs", ":", "\"PairSet\"", ",", "parent_type", ":", "Optional", "[", "GraphQLNamedType", "]", ",", "selec...
Find conflicts within selection set. Find all conflicts found "within" a selection set, including those found via spreading in fragments. Called when visiting each SelectionSet in the GraphQL Document.
[ "Find", "conflicts", "within", "selection", "set", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L160-L220
226,189
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
collect_conflicts_between_fields_and_fragment
def collect_conflicts_between_fields_and_fragment( context: ValidationContext, conflicts: List[Conflict], cached_fields_and_fragment_names: Dict, compared_fragments: Set[str], compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, field_map: NodeAndDefCollection, fragment_name: str, ) -> None: """Collect conflicts between fields and fragment. Collect all conflicts found between a set of fields and a fragment reference including via spreading in any nested fragments. """ # Memoize so a fragment is not compared for conflicts more than once. if fragment_name in compared_fragments: return compared_fragments.add(fragment_name) fragment = context.get_fragment(fragment_name) if not fragment: return None field_map2, fragment_names2 = get_referenced_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment ) # Do not compare a fragment's fieldMap to itself. if field_map is field_map2: return # (D) First collect any conflicts between the provided collection of fields and the # collection of fields represented by the given fragment. collect_conflicts_between( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, field_map, field_map2, ) # (E) Then collect any conflicts between the provided collection of fields and any # fragment names found in the given fragment. for fragment_name2 in fragment_names2: collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, are_mutually_exclusive, field_map, fragment_name2, )
python
def collect_conflicts_between_fields_and_fragment( context: ValidationContext, conflicts: List[Conflict], cached_fields_and_fragment_names: Dict, compared_fragments: Set[str], compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, field_map: NodeAndDefCollection, fragment_name: str, ) -> None: # Memoize so a fragment is not compared for conflicts more than once. if fragment_name in compared_fragments: return compared_fragments.add(fragment_name) fragment = context.get_fragment(fragment_name) if not fragment: return None field_map2, fragment_names2 = get_referenced_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment ) # Do not compare a fragment's fieldMap to itself. if field_map is field_map2: return # (D) First collect any conflicts between the provided collection of fields and the # collection of fields represented by the given fragment. collect_conflicts_between( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, field_map, field_map2, ) # (E) Then collect any conflicts between the provided collection of fields and any # fragment names found in the given fragment. for fragment_name2 in fragment_names2: collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, are_mutually_exclusive, field_map, fragment_name2, )
[ "def", "collect_conflicts_between_fields_and_fragment", "(", "context", ":", "ValidationContext", ",", "conflicts", ":", "List", "[", "Conflict", "]", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "compared_fragments", ":", "Set", "[", "str", "]", ",", ...
Collect conflicts between fields and fragment. Collect all conflicts found between a set of fields and a fragment reference including via spreading in any nested fragments.
[ "Collect", "conflicts", "between", "fields", "and", "fragment", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L223-L279
226,190
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
collect_conflicts_between_fragments
def collect_conflicts_between_fragments( context: ValidationContext, conflicts: List[Conflict], cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, fragment_name1: str, fragment_name2: str, ) -> None: """Collect conflicts between fragments. Collect all conflicts found between two fragments, including via spreading in any nested fragments. """ # No need to compare a fragment to itself. if fragment_name1 == fragment_name2: return # Memoize so two fragments are not compared for conflicts more than once. if compared_fragment_pairs.has( fragment_name1, fragment_name2, are_mutually_exclusive ): return compared_fragment_pairs.add(fragment_name1, fragment_name2, are_mutually_exclusive) fragment1 = context.get_fragment(fragment_name1) fragment2 = context.get_fragment(fragment_name2) if not fragment1 or not fragment2: return None field_map1, fragment_names1 = get_referenced_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment1 ) field_map2, fragment_names2 = get_referenced_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment2 ) # (F) First, collect all conflicts between these two collections of fields # (not including any nested fragments) collect_conflicts_between( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, field_map1, field_map2, ) # (G) Then collect conflicts between the first fragment and any nested fragments # spread in the second fragment. for nested_fragment_name2 in fragment_names2: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, fragment_name1, nested_fragment_name2, ) # (G) Then collect conflicts between the second fragment and any nested fragments # spread in the first fragment. for nested_fragment_name1 in fragment_names1: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, nested_fragment_name1, fragment_name2, )
python
def collect_conflicts_between_fragments( context: ValidationContext, conflicts: List[Conflict], cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, fragment_name1: str, fragment_name2: str, ) -> None: # No need to compare a fragment to itself. if fragment_name1 == fragment_name2: return # Memoize so two fragments are not compared for conflicts more than once. if compared_fragment_pairs.has( fragment_name1, fragment_name2, are_mutually_exclusive ): return compared_fragment_pairs.add(fragment_name1, fragment_name2, are_mutually_exclusive) fragment1 = context.get_fragment(fragment_name1) fragment2 = context.get_fragment(fragment_name2) if not fragment1 or not fragment2: return None field_map1, fragment_names1 = get_referenced_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment1 ) field_map2, fragment_names2 = get_referenced_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment2 ) # (F) First, collect all conflicts between these two collections of fields # (not including any nested fragments) collect_conflicts_between( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, field_map1, field_map2, ) # (G) Then collect conflicts between the first fragment and any nested fragments # spread in the second fragment. for nested_fragment_name2 in fragment_names2: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, fragment_name1, nested_fragment_name2, ) # (G) Then collect conflicts between the second fragment and any nested fragments # spread in the first fragment. for nested_fragment_name1 in fragment_names1: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, nested_fragment_name1, fragment_name2, )
[ "def", "collect_conflicts_between_fragments", "(", "context", ":", "ValidationContext", ",", "conflicts", ":", "List", "[", "Conflict", "]", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "compared_fragment_pairs", ":", "\"PairSet\"", ",", "are_mutually_exclus...
Collect conflicts between fragments. Collect all conflicts found between two fragments, including via spreading in any nested fragments.
[ "Collect", "conflicts", "between", "fragments", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L282-L356
226,191
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
find_conflicts_between_sub_selection_sets
def find_conflicts_between_sub_selection_sets( context: ValidationContext, cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, parent_type1: Optional[GraphQLNamedType], selection_set1: SelectionSetNode, parent_type2: Optional[GraphQLNamedType], selection_set2: SelectionSetNode, ) -> List[Conflict]: """Find conflicts between sub selection sets. Find all conflicts found between two selection sets, including those found via spreading in fragments. Called when determining if conflicts exist between the sub-fields of two overlapping fields. """ conflicts: List[Conflict] = [] field_map1, fragment_names1 = get_fields_and_fragment_names( context, cached_fields_and_fragment_names, parent_type1, selection_set1 ) field_map2, fragment_names2 = get_fields_and_fragment_names( context, cached_fields_and_fragment_names, parent_type2, selection_set2 ) # (H) First, collect all conflicts between these two collections of field. collect_conflicts_between( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, field_map1, field_map2, ) # (I) Then collect conflicts between the first collection of fields and those # referenced by each fragment name associated with the second. if fragment_names2: compared_fragments: Set[str] = set() for fragment_name2 in fragment_names2: collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, are_mutually_exclusive, field_map1, fragment_name2, ) # (I) Then collect conflicts between the second collection of fields and those # referenced by each fragment name associated with the first. if fragment_names1: compared_fragments = set() for fragment_name1 in fragment_names1: collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, are_mutually_exclusive, field_map2, fragment_name1, ) # (J) Also collect conflicts between any fragment names by the first and fragment # names by the second. This compares each item in the first set of names to each # item in the second set of names. for fragment_name1 in fragment_names1: for fragment_name2 in fragment_names2: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, fragment_name1, fragment_name2, ) return conflicts
python
def find_conflicts_between_sub_selection_sets( context: ValidationContext, cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, parent_type1: Optional[GraphQLNamedType], selection_set1: SelectionSetNode, parent_type2: Optional[GraphQLNamedType], selection_set2: SelectionSetNode, ) -> List[Conflict]: conflicts: List[Conflict] = [] field_map1, fragment_names1 = get_fields_and_fragment_names( context, cached_fields_and_fragment_names, parent_type1, selection_set1 ) field_map2, fragment_names2 = get_fields_and_fragment_names( context, cached_fields_and_fragment_names, parent_type2, selection_set2 ) # (H) First, collect all conflicts between these two collections of field. collect_conflicts_between( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, field_map1, field_map2, ) # (I) Then collect conflicts between the first collection of fields and those # referenced by each fragment name associated with the second. if fragment_names2: compared_fragments: Set[str] = set() for fragment_name2 in fragment_names2: collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, are_mutually_exclusive, field_map1, fragment_name2, ) # (I) Then collect conflicts between the second collection of fields and those # referenced by each fragment name associated with the first. if fragment_names1: compared_fragments = set() for fragment_name1 in fragment_names1: collect_conflicts_between_fields_and_fragment( context, conflicts, cached_fields_and_fragment_names, compared_fragments, compared_fragment_pairs, are_mutually_exclusive, field_map2, fragment_name1, ) # (J) Also collect conflicts between any fragment names by the first and fragment # names by the second. This compares each item in the first set of names to each # item in the second set of names. for fragment_name1 in fragment_names1: for fragment_name2 in fragment_names2: collect_conflicts_between_fragments( context, conflicts, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, fragment_name1, fragment_name2, ) return conflicts
[ "def", "find_conflicts_between_sub_selection_sets", "(", "context", ":", "ValidationContext", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "compared_fragment_pairs", ":", "\"PairSet\"", ",", "are_mutually_exclusive", ":", "bool", ",", "parent_type1", ":", "Opt...
Find conflicts between sub selection sets. Find all conflicts found between two selection sets, including those found via spreading in fragments. Called when determining if conflicts exist between the sub-fields of two overlapping fields.
[ "Find", "conflicts", "between", "sub", "selection", "sets", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L359-L442
226,192
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
find_conflict
def find_conflict( context: ValidationContext, cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", parent_fields_are_mutually_exclusive: bool, response_name: str, field1: NodeAndDef, field2: NodeAndDef, ) -> Optional[Conflict]: """Find conflict. Determines if there is a conflict between two particular fields, including comparing their sub-fields. """ parent_type1, node1, def1 = field1 parent_type2, node2, def2 = field2 # If it is known that two fields could not possibly apply at the same time, due to # the parent types, then it is safe to permit them to diverge in aliased field or # arguments used as they will not present any ambiguity by differing. It is known # that two parent types could never overlap if they are different Object types. # Interface or Union types might overlap - if not in the current state of the # schema, then perhaps in some future version, thus may not safely diverge. are_mutually_exclusive = parent_fields_are_mutually_exclusive or ( parent_type1 != parent_type2 and is_object_type(parent_type1) and is_object_type(parent_type2) ) # The return type for each field. type1 = cast(Optional[GraphQLOutputType], def1 and def1.type) type2 = cast(Optional[GraphQLOutputType], def2 and def2.type) if not are_mutually_exclusive: # Two aliases must refer to the same field. name1 = node1.name.value name2 = node2.name.value if name1 != name2: return ( (response_name, f"{name1} and {name2} are different fields"), [node1], [node2], ) # Two field calls must have the same arguments. if not same_arguments(node1.arguments or [], node2.arguments or []): return (response_name, "they have differing arguments"), [node1], [node2] if type1 and type2 and do_types_conflict(type1, type2): return ( (response_name, f"they return conflicting types {type1} and {type2}"), [node1], [node2], ) # Collect and compare sub-fields. Use the same "visited fragment names" list for # both collections so fields in a fragment reference are never compared to # themselves. selection_set1 = node1.selection_set selection_set2 = node2.selection_set if selection_set1 and selection_set2: conflicts = find_conflicts_between_sub_selection_sets( context, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, get_named_type(type1), selection_set1, get_named_type(type2), selection_set2, ) return subfield_conflicts(conflicts, response_name, node1, node2) return None
python
def find_conflict( context: ValidationContext, cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", parent_fields_are_mutually_exclusive: bool, response_name: str, field1: NodeAndDef, field2: NodeAndDef, ) -> Optional[Conflict]: parent_type1, node1, def1 = field1 parent_type2, node2, def2 = field2 # If it is known that two fields could not possibly apply at the same time, due to # the parent types, then it is safe to permit them to diverge in aliased field or # arguments used as they will not present any ambiguity by differing. It is known # that two parent types could never overlap if they are different Object types. # Interface or Union types might overlap - if not in the current state of the # schema, then perhaps in some future version, thus may not safely diverge. are_mutually_exclusive = parent_fields_are_mutually_exclusive or ( parent_type1 != parent_type2 and is_object_type(parent_type1) and is_object_type(parent_type2) ) # The return type for each field. type1 = cast(Optional[GraphQLOutputType], def1 and def1.type) type2 = cast(Optional[GraphQLOutputType], def2 and def2.type) if not are_mutually_exclusive: # Two aliases must refer to the same field. name1 = node1.name.value name2 = node2.name.value if name1 != name2: return ( (response_name, f"{name1} and {name2} are different fields"), [node1], [node2], ) # Two field calls must have the same arguments. if not same_arguments(node1.arguments or [], node2.arguments or []): return (response_name, "they have differing arguments"), [node1], [node2] if type1 and type2 and do_types_conflict(type1, type2): return ( (response_name, f"they return conflicting types {type1} and {type2}"), [node1], [node2], ) # Collect and compare sub-fields. Use the same "visited fragment names" list for # both collections so fields in a fragment reference are never compared to # themselves. selection_set1 = node1.selection_set selection_set2 = node2.selection_set if selection_set1 and selection_set2: conflicts = find_conflicts_between_sub_selection_sets( context, cached_fields_and_fragment_names, compared_fragment_pairs, are_mutually_exclusive, get_named_type(type1), selection_set1, get_named_type(type2), selection_set2, ) return subfield_conflicts(conflicts, response_name, node1, node2) return None
[ "def", "find_conflict", "(", "context", ":", "ValidationContext", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "compared_fragment_pairs", ":", "\"PairSet\"", ",", "parent_fields_are_mutually_exclusive", ":", "bool", ",", "response_name", ":", "str", ",", "...
Find conflict. Determines if there is a conflict between two particular fields, including comparing their sub-fields.
[ "Find", "conflict", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L517-L590
226,193
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
do_types_conflict
def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool: """Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List and Non-Null types must match. """ if is_list_type(type1): return ( do_types_conflict( cast(GraphQLList, type1).of_type, cast(GraphQLList, type2).of_type ) if is_list_type(type2) else True ) if is_list_type(type2): return True if is_non_null_type(type1): return ( do_types_conflict( cast(GraphQLNonNull, type1).of_type, cast(GraphQLNonNull, type2).of_type ) if is_non_null_type(type2) else True ) if is_non_null_type(type2): return True if is_leaf_type(type1) or is_leaf_type(type2): return type1 is not type2 return False
python
def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool: if is_list_type(type1): return ( do_types_conflict( cast(GraphQLList, type1).of_type, cast(GraphQLList, type2).of_type ) if is_list_type(type2) else True ) if is_list_type(type2): return True if is_non_null_type(type1): return ( do_types_conflict( cast(GraphQLNonNull, type1).of_type, cast(GraphQLNonNull, type2).of_type ) if is_non_null_type(type2) else True ) if is_non_null_type(type2): return True if is_leaf_type(type1) or is_leaf_type(type2): return type1 is not type2 return False
[ "def", "do_types_conflict", "(", "type1", ":", "GraphQLOutputType", ",", "type2", ":", "GraphQLOutputType", ")", "->", "bool", ":", "if", "is_list_type", "(", "type1", ")", ":", "return", "(", "do_types_conflict", "(", "cast", "(", "GraphQLList", ",", "type1",...
Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List and Non-Null types must match.
[ "Check", "whether", "two", "types", "conflict" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L613-L642
226,194
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
get_fields_and_fragment_names
def get_fields_and_fragment_names( context: ValidationContext, cached_fields_and_fragment_names: Dict, parent_type: Optional[GraphQLNamedType], selection_set: SelectionSetNode, ) -> Tuple[NodeAndDefCollection, List[str]]: """Get fields and referenced fragment names Given a selection set, return the collection of fields (a mapping of response name to field nodes and definitions) as well as a list of fragment names referenced via fragment spreads. """ cached = cached_fields_and_fragment_names.get(selection_set) if not cached: node_and_defs: NodeAndDefCollection = {} fragment_names: Dict[str, bool] = {} collect_fields_and_fragment_names( context, parent_type, selection_set, node_and_defs, fragment_names ) cached = (node_and_defs, list(fragment_names)) cached_fields_and_fragment_names[selection_set] = cached return cached
python
def get_fields_and_fragment_names( context: ValidationContext, cached_fields_and_fragment_names: Dict, parent_type: Optional[GraphQLNamedType], selection_set: SelectionSetNode, ) -> Tuple[NodeAndDefCollection, List[str]]: cached = cached_fields_and_fragment_names.get(selection_set) if not cached: node_and_defs: NodeAndDefCollection = {} fragment_names: Dict[str, bool] = {} collect_fields_and_fragment_names( context, parent_type, selection_set, node_and_defs, fragment_names ) cached = (node_and_defs, list(fragment_names)) cached_fields_and_fragment_names[selection_set] = cached return cached
[ "def", "get_fields_and_fragment_names", "(", "context", ":", "ValidationContext", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "parent_type", ":", "Optional", "[", "GraphQLNamedType", "]", ",", "selection_set", ":", "SelectionSetNode", ",", ")", "->", "T...
Get fields and referenced fragment names Given a selection set, return the collection of fields (a mapping of response name to field nodes and definitions) as well as a list of fragment names referenced via fragment spreads.
[ "Get", "fields", "and", "referenced", "fragment", "names" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L645-L666
226,195
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
get_referenced_fields_and_fragment_names
def get_referenced_fields_and_fragment_names( context: ValidationContext, cached_fields_and_fragment_names: Dict, fragment: FragmentDefinitionNode, ) -> Tuple[NodeAndDefCollection, List[str]]: """Get referenced fields and nested fragment names Given a reference to a fragment, return the represented collection of fields as well as a list of nested fragment names referenced via fragment spreads. """ # Short-circuit building a type from the node if possible. cached = cached_fields_and_fragment_names.get(fragment.selection_set) if cached: return cached fragment_type = type_from_ast(context.schema, fragment.type_condition) return get_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment_type, fragment.selection_set )
python
def get_referenced_fields_and_fragment_names( context: ValidationContext, cached_fields_and_fragment_names: Dict, fragment: FragmentDefinitionNode, ) -> Tuple[NodeAndDefCollection, List[str]]: # Short-circuit building a type from the node if possible. cached = cached_fields_and_fragment_names.get(fragment.selection_set) if cached: return cached fragment_type = type_from_ast(context.schema, fragment.type_condition) return get_fields_and_fragment_names( context, cached_fields_and_fragment_names, fragment_type, fragment.selection_set )
[ "def", "get_referenced_fields_and_fragment_names", "(", "context", ":", "ValidationContext", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "fragment", ":", "FragmentDefinitionNode", ",", ")", "->", "Tuple", "[", "NodeAndDefCollection", ",", "List", "[", "st...
Get referenced fields and nested fragment names Given a reference to a fragment, return the represented collection of fields as well as a list of nested fragment names referenced via fragment spreads.
[ "Get", "referenced", "fields", "and", "nested", "fragment", "names" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L669-L687
226,196
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
subfield_conflicts
def subfield_conflicts( conflicts: List[Conflict], response_name: str, node1: FieldNode, node2: FieldNode ) -> Optional[Conflict]: """Check whether there are conflicts between sub-fields. Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict. """ if conflicts: return ( (response_name, [conflict[0] for conflict in conflicts]), list(chain([node1], *[conflict[1] for conflict in conflicts])), list(chain([node2], *[conflict[2] for conflict in conflicts])), ) return None
python
def subfield_conflicts( conflicts: List[Conflict], response_name: str, node1: FieldNode, node2: FieldNode ) -> Optional[Conflict]: if conflicts: return ( (response_name, [conflict[0] for conflict in conflicts]), list(chain([node1], *[conflict[1] for conflict in conflicts])), list(chain([node2], *[conflict[2] for conflict in conflicts])), ) return None
[ "def", "subfield_conflicts", "(", "conflicts", ":", "List", "[", "Conflict", "]", ",", "response_name", ":", "str", ",", "node1", ":", "FieldNode", ",", "node2", ":", "FieldNode", ")", "->", "Optional", "[", "Conflict", "]", ":", "if", "conflicts", ":", ...
Check whether there are conflicts between sub-fields. Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict.
[ "Check", "whether", "there", "are", "conflicts", "between", "sub", "-", "fields", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L729-L743
226,197
graphql-python/graphql-core-next
graphql/pyutils/event_emitter.py
EventEmitter.add_listener
def add_listener(self, event_name: str, listener: Callable): """Add a listener.""" self.listeners[event_name].append(listener) return self
python
def add_listener(self, event_name: str, listener: Callable): self.listeners[event_name].append(listener) return self
[ "def", "add_listener", "(", "self", ",", "event_name", ":", "str", ",", "listener", ":", "Callable", ")", ":", "self", ".", "listeners", "[", "event_name", "]", ".", "append", "(", "listener", ")", "return", "self" ]
Add a listener.
[ "Add", "a", "listener", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/event_emitter.py#L18-L21
226,198
graphql-python/graphql-core-next
graphql/pyutils/event_emitter.py
EventEmitter.remove_listener
def remove_listener(self, event_name, listener): """Removes a listener.""" self.listeners[event_name].remove(listener) return self
python
def remove_listener(self, event_name, listener): self.listeners[event_name].remove(listener) return self
[ "def", "remove_listener", "(", "self", ",", "event_name", ",", "listener", ")", ":", "self", ".", "listeners", "[", "event_name", "]", ".", "remove", "(", "listener", ")", "return", "self" ]
Removes a listener.
[ "Removes", "a", "listener", "." ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/event_emitter.py#L23-L26
226,199
graphql-python/graphql-core-next
graphql/utilities/introspection_from_schema.py
introspection_from_schema
def introspection_from_schema( schema: GraphQLSchema, descriptions: bool = True ) -> IntrospectionSchema: """Build an IntrospectionQuery from a GraphQLSchema IntrospectionQuery is useful for utilities that care about type and field relationships, but do not need to traverse through those relationships. This is the inverse of build_client_schema. The primary use case is outside of the server context, for instance when doing schema comparisons. """ query_ast = parse(get_introspection_query(descriptions)) from ..execution.execute import execute, ExecutionResult result = execute(schema, query_ast) if not isinstance(result, ExecutionResult): raise RuntimeError("Introspection cannot be executed") if result.errors or not result.data: raise result.errors[0] if result.errors else GraphQLError( "Introspection did not return a result" ) return result.data
python
def introspection_from_schema( schema: GraphQLSchema, descriptions: bool = True ) -> IntrospectionSchema: query_ast = parse(get_introspection_query(descriptions)) from ..execution.execute import execute, ExecutionResult result = execute(schema, query_ast) if not isinstance(result, ExecutionResult): raise RuntimeError("Introspection cannot be executed") if result.errors or not result.data: raise result.errors[0] if result.errors else GraphQLError( "Introspection did not return a result" ) return result.data
[ "def", "introspection_from_schema", "(", "schema", ":", "GraphQLSchema", ",", "descriptions", ":", "bool", "=", "True", ")", "->", "IntrospectionSchema", ":", "query_ast", "=", "parse", "(", "get_introspection_query", "(", "descriptions", ")", ")", "from", ".", ...
Build an IntrospectionQuery from a GraphQLSchema IntrospectionQuery is useful for utilities that care about type and field relationships, but do not need to traverse through those relationships. This is the inverse of build_client_schema. The primary use case is outside of the server context, for instance when doing schema comparisons.
[ "Build", "an", "IntrospectionQuery", "from", "a", "GraphQLSchema" ]
073dce3f002f897d40f9348ffd8f107815160540
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/introspection_from_schema.py#L14-L36