py_gql.lang#

py_gql.lang

The py_gql.lang module is responsible for parsing and operating on the GraphQL language and source files.

You can refer to the relevant part of the spec for more information.

py_gql.lang.parse(source, **kwargs)[source]#

Parse a string as a GraphQL Document.

Parameters:
  • source (Union[str, bytes]) – source document.
  • **kwargs – Remaining keyword arguments passed to Parser
Raises:

GraphQLSyntaxError – if a syntax error is encountered.

Returns:

Parsed document.

Return type:

py_gql.lang.ast.Document

py_gql.lang.parse_type(source, **kwargs)[source]#

Parse a string as a single GraphQL type.

This is useful within tools that operate upon GraphQL types (e.g. [Int!]) directly and in isolation of complete GraphQL documents such as when building a schema from the SDL or stitching schemas together.

Parameters:
  • source (Union[str, bytes]) – source document
  • **kwargs – Remaining keyword arguments passed to Parser
Return type:

Type

Returns:

Parsed value node.

Raises:

GraphQLSyntaxError

py_gql.lang.parse_value(source, **kwargs)[source]#

Parse a string as a single GraphQL value.

This is useful within tools that operate upon GraphQL values (e.g. [42]) directly and in isolation of complete GraphQL documents. Consider providing the results to the utility functions py_gql.utilities.untyped_value_from_ast() and py_gql.utilities.value_from_ast().

Parameters:
  • source (Union[str, bytes]) – source document
  • **kwargs – Remaining keyword arguments passed to Parser
Raises:

GraphQLSyntaxError – if a syntax error is encountered.

Return type:

Union[Variable, Value]

Returns:

Parsed value node.

Raises:

GraphQLSyntaxError

py_gql.lang.print_ast(node, indent=2, include_descriptions=True)[source]#

Convert an AST node into a string, using reasonable formatting rules.

Parameters:
  • node (py_gql.lang.ast.Node) – Node to format.
  • indent (int) – Indent character or number of spaces.
  • include_descriptions (bool) – If True include descriptions as leading block strings in the output. Only relevant for SDL nodes.
Returns:

Return type:

str

class py_gql.lang.Parser(source, no_location=False, allow_type_system=False, experimental_fragment_variables=False)[source]#

GraphQL syntax parser.

Call parse_document() to parse a GraphQL document.

All parse_* methods will raise GraphQLSyntaxError if a syntax error is encountered.

Parameters:
  • source (Union[str, bytes]) – source document
  • no_location (bool) – By default, the parser creates AST nodes that know the location in the source that they correspond to. This configuration flag disables that behavior for performance or testing reasons.
  • allow_type_system (bool) – By default, the parser will accept schema definition nodes, when only executing GraphQL queries setting this to False can save operations and remove the need for some later validation.
  • experimental_fragment_variables (bool) –

    If enabled, the parser will understand and parse variable definitions contained in a fragment definition. They’ll be represented in the variable_definitions field of the FragmentDefinition.

    The syntax is identical to normal, query-defined variables, for example:

    fragment A($var: Boolean = false) on T  {
        ...
    }
    

    Warning

    This feature is experimental and may change or be removed in the future. See https://github.com/graphql/graphql-spec/issues/204 for the open spec PR.

advance()[source]#

Move parsing window forward and return the next token.

Return type:Token
Returns:Token
Raises:UnexpectedEOF – if there is not enough tokens left in the lexer.
any_(open_kind, parse_fn, close_kind)[source]#

Parse a list of nodes surrounded by open_kind and close_kind.

This advances the parser to the next token after the closing token.

Parameters:
Return type:

List[~N]

Returns:

List of parsed nodes.

Raises:

UnexpectedToken – if opening, entry or closing token do not match.

delimited_list(delimiter, parse_fn)[source]#

Parse a list of nodes separated by delimiter tokens.

Advances the parser to the next token after the last token.

Parameters:
  • delimiter (Type[Token]) – Delimiter kind. Must be a subclass of py_gql.lang.token.Token
  • parse_fn (callable) – Function to call for every item, should be a method of the Parser instance.
Return type:

List[~N]

Returns:

List of parsed nodes.

Raises:

UnexpectedToken – if opening, entry or closing token do not match.

expect(kind)[source]#

Advance the parser asserting the kind of the the next token.

Parameters:kind (Type[Token]) – Expected token kind. Must be a subclass of py_gql.lang.token.Token
Return type:Token
Returns:Token
Raises:UnexpectedToken – If the next token is not of the given kind.
expect_keyword(keyword)[source]#

Advance the parser asserting that the next token is a specific Name.

Parameters:keyword (str) – Expected keyword
Return type:Name
Returns:Name token
Raises:UnexpectedToken – If the next token is not a name with the given value.
many(open_kind, parse_fn, close_kind)[source]#

Parse a non-empty list of nodes surrounded by open_kind and close_kind.

This advances the parser to the next token after the closing token.

Parameters:
Return type:

List[~N]

Returns:

List of parsed nodes.

Raises:

UnexpectedToken – if opening, entry or closing token do not match.

parse_argument(const=False)[source]#

Argument[Const] : Name : Value[?Const]

Return type:Argument
parse_argument_definitions()[source]#

ArgumentsDefinition : ( InputValueDefinition+ )

Return type:List[InputValueDefinition]
parse_arguments(const=False)[source]#

Arguments[Const] : ( Argument[?Const]+ )

Return type:List[Argument]
parse_definition()[source]#

Definition : ExecutableDefinition | TypeSystemDefinition

Ignores type system definitions if allow_type_system was set to False.

Return type:Definition
parse_description()[source]#

Description : StringValue

Return type:Optional[StringValue]
parse_directive(const=False)[source]#

Directive[Const] : @ Name Arguments[?Const]?

Return type:Directive
parse_directive_definition()[source]#
DirectiveDefinition :
Description? directive @ Name ArgumentsDefinition? on DirectiveLocations
Return type:DirectiveDefinition
parse_directive_location()[source]#
DirectiveLocation :
ExecutableDirectiveLocation | TypeSystemDirectiveLocation
  • ExecutableDirectiveLocation : one of QUERY MUTATION SUBSCRIPTION FIELD
    FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT
  • TypeSystemDirectiveLocation : one of SCHEMA SCALAR OBJECT
    FIELD_DEFINITION ARGUMENT_DEFINITION INTERFACE UNION ENUM ENUM_VALUE INPUT_OBJECT INPUT_FIELD_DEFINITION
Return type:Name
parse_directive_locations()[source]#
DirectiveLocations :
|? DirectiveLocation | DirectiveLocations | DirectiveLocation
Return type:List[Name]
parse_directives(const=False)[source]#

Directives[Const] : Directive[?Const]+

Return type:List[Directive]
parse_document()[source]#

Document : Definition+

Return type:Document
parse_enum_type_definition()[source]#
EnumTypeDefinition :
Description? enum Name Directives[Const]? EnumValuesDefinition?
Return type:EnumTypeDefinition
parse_enum_type_extension()[source]#
EnumTypeExtension :
extend enum Name Directives[Const]? EnumValuesDefinition | extend enum Name Directives[Const]
Return type:EnumTypeExtension
parse_enum_value_definition()[source]#

EnumValueDefinition : Description? EnumValue Directives[Const]?

  • EnumValue : Name
Return type:EnumValueDefinition
parse_enum_values_definition()[source]#

EnumValuesDefinition : { EnumValueDefinition+ }

Return type:List[EnumValueDefinition]
parse_executable_definition()[source]#

ExecutableDefinition : OperationDefinition | FragmentDefinition

Return type:ExecutableDefinition
parse_field()[source]#

Field : Alias? Name Arguments? Directives? SelectionSet?

  • Alias : Name :
Return type:Field
parse_field_definition()[source]#
FieldDefinition :
Description? Name ArgumentsDefinition? : Type Directives[Const]?
Return type:FieldDefinition
parse_fields_definition()[source]#

FieldsDefinition : { FieldDefinition+ }

Return type:List[FieldDefinition]
parse_fragment()[source]#

FragmeSpread | InlineFragment

  • FragmentSpread : … FragmentName Directives?
  • InlineFragment : … TypeCondition? Directives? SelectionSet
Return type:Union[InlineFragment, FragmentSpread]
parse_fragment_definition()[source]#
FragmentDefinition :
fragment FragmentName on TypeCondition Directives? SelectionSet
  • TypeCondition : NamedType
Return type:FragmentDefinition
parse_fragment_name()[source]#

FragmentName : Name but not “on”

Return type:Name
parse_implements_interfaces()[source]#
ImplementsInterfaces :
implements &? NamedType | ImplementsInterfaces & NamedType
Return type:List[NamedType]
parse_input_fields_definition()[source]#

InputFieldsDefinition : { InputValueDefinition+ }

Return type:List[InputValueDefinition]
parse_input_object_type_definition()[source]#
InputObjectTypeDefinition :
Description? input Name Directives[Const]? InputFieldsDefinition?
Return type:InputObjectTypeDefinition
parse_input_object_type_extension()[source]#
InputObjectTypeExtension :
extend input Name Directives[Const]? InputFieldsDefinition | extend input Name Directives[Const]
Return type:InputObjectTypeExtension
parse_input_value_definition()[source]#
InputValueDefinition :
Description? Name : Type DefaultValue? Directives[Const]?
Return type:InputValueDefinition
parse_interface_type_definition()[source]#
InterfaceTypeDefinition :
Description? interface Name Directives[Const]? FieldsDefinition?
Return type:InterfaceTypeDefinition
parse_interface_type_extension()[source]#
InterfaceTypeExtension :
extend interface Name Directives[Const]? FieldsDefinition | extend interface Name Directives[Const]
Return type:InterfaceTypeExtension
parse_list(const=False)[source]#

ListValue[Const] : [ ] | [ Value[?Const]+ ]

Return type:ListValue
parse_name()[source]#

Convert a name token into a name parse node.

Return type:Name
parse_named_type()[source]#

NamedType : Name

Return type:NamedType
parse_object(const=False)[source]#

ObjectValue[Const] { } | { ObjectField[?Const]+ }

Return type:ObjectValue
parse_object_field(const=False)[source]#

ObjectField[Const] : Name : Value[?Const]

Return type:ObjectField
parse_object_type_definition()[source]#
ObjectTypeDefinition :
Description? type Name ImplementsInterfaces? Directives[Const]?
FieldsDefinition?
Return type:ObjectTypeDefinition
parse_object_type_extension()[source]#
ObjectTypeExtension :
extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition | extend type Name ImplementsInterfaces? Directives[Const] | extend type Name ImplementsInterfaces
Return type:ObjectTypeExtension
parse_operation_definition()[source]#
OperationDefinition :
SelectionSet | OperationType Name? VariableDefinitions? Directives? SelectionSet
Return type:OperationDefinition
parse_operation_type()[source]#

OperationType : one of “query” “mutation” “subscription”

Return type:str
parse_operation_type_definition()[source]#

OperationTypeDefinition : OperationType : NamedType

Return type:OperationTypeDefinition
parse_scalar_type_definition()[source]#

ScalarTypeDefinition : Description? scalar Name Directives[Const]?

Return type:ScalarTypeDefinition
parse_scalar_type_extension()[source]#

ScalarTypeExtension : extend scalar Name Directives[Const]

Return type:ScalarTypeExtension
parse_schema_definition()[source]#

SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ }

Return type:SchemaDefinition
parse_schema_extension()[source]#
SchemaExtension :
extend schema Directives[Const] { [OperationTypeDefinition] } | extend schema Directives[Const]
Return type:SchemaExtension
parse_selection()[source]#

Selection : Field | FragmentSpread | InlineFragment

Return type:Selection
parse_selection_set()[source]#

SelectionSet : { Selection+ }

Return type:SelectionSet
parse_type_reference()[source]#

Type : NamedType | ListType | NonNullType

Return type:Type
parse_type_system_definition()[source]#
TypeSystemDefinition :
SchemaDefinition | TypeDefinition | TypeExtension | DirectiveDefinition
  • TypeDefinition :
    ScalarTypeDefinition | ObjectTypeDefinition | InterfaceTypeDefinition | UnionTypeDefinition | EnumTypeDefinition | InputObjectTypeDefinition
Return type:TypeSystemDefinition
parse_type_system_extension()[source]#

TypeSystemExtension : SchemaExtension | TypeExtension

  • TypeExtension :
    ScalarTypeExtension | ObjectTypeExtension | InterfaceTypeExtension | UnionTypeExtension | EnumTypeExtension | InputObjectTypeDefinition
Return type:TypeSystemExtension
parse_union_member_types()[source]#

UnionMemberTypes : = |? NamedType | UnionMemberTypes | NamedType

Return type:List[NamedType]
parse_union_type_definition()[source]#
UnionTypeDefinition :
Description? union Name Directives[Const]? UnionMemberTypes?
Return type:UnionTypeDefinition
parse_union_type_extension()[source]#
UnionTypeExtension :
extend union Name Directives[Const]? UnionMemberTypes | extend union Name Directives[Const]
Return type:UnionTypeExtension
parse_value_literal(const=False)[source]#
Value[Const] :
[~Const]Variable | IntValue | FloatValue | StringValue | BooleanValue | NullValue | EnumValue | ListValue[?Const] | ObjectValue[?Const]
  • BooleanValue : one of “true” “false”
  • NullValue : “null”
  • EnumValue : Name but not “true”, “false” or “null”
Return type:Union[Value, Variable]
parse_variable()[source]#

Variable : $ Name

Return type:Variable
parse_variable_definition()[source]#

VariableDefinition : Variable : Type DefaultValue? Directives[Const]?

Return type:VariableDefinition
parse_variable_definitions()[source]#

VariableDefinitions : ( VariableDefinition+ )

Return type:List[VariableDefinition]
peek(count=1)[source]#

Look at a token ahead of the current position without advancing the parser.

Parameters:count (int) – How many tokens should we look ahead
Return type:Token
Returns:Token
Raises:UnexpectedEOF – if there is not enough tokens left in the lexer.
skip(kind)[source]#

Conditionally advance the parser.

Parameters:kind (Type[Token]) – Token kind to read over. Must be a subclass of py_gql.lang.token.Token
Return type:bool
Returns:True if the next token was of the given kind and we’ve advanced the parser, False otherwise.
class py_gql.lang.Lexer(source)[source]#

Iterable GraphQL language lexer / tokenizer.

This class is not typically exposed through the parser but can be used independently to build custom parsers.

Each call to __next__ will read over a number of characters required to form a valid py_gql.lang.token.Token and otherwise raise GraphQLSyntaxError if that is not possible.

Parameters:source (Union[str, bytes]) – Source string. bytes objects will be converted to Unicode.