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.

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. Bytestrings will be converted to unicode.

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.

peek(count=1)[source]#

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

Parameters

count (int) – How many tokens should we look ahead

:raises UnexpectedEOF: if there is not enough tokens left in the lexer.

Return type

Token

advance()[source]#

Move parsing window forward and return the next token.

:raises UnexpectedEOF: if there is not enough tokens left in the lexer.

Return type

Token

expect(kind)[source]#

Advance the parser and check that the next token is of the given token class otherwise raises UnexpectedToken.

Parameters

kind (Type[Token]) – Expected token kind. Must be a subclass of py_gql.lang.token.Token

Return type

Token

expect_keyword(keyword)[source]#

Advance the parser and check that the next token is a Name with the given value otherwise raises UnexpectedToken.

Parameters

keyword (str) – Expected keyword

Return type

Name

skip(kind)[source]#

If the next token is of the given kind, return True after advancing the parser. Otherwise, do not change the parser state and return False.

Parameters

kind (Type[Token]) – Token kind to read over. Must be a subclass of py_gql.lang.token.Token

Return type

bool

many(open_kind, parse_fn, close_kind)[source]#

Return a non-empty list of parse nodes, determined by parse_fn which are surrounded by open_kind and close_kind tokens. Advances the parser to the next lex token after the closing token.

Parameters

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

Return type

List[~N]

any_(open_kind, parse_fn, close_kind)[source]#

Return a non-empty list of parse nodes, determined by parse_fn which are surrounded by open_kind and close_kind tokens. Advances the parser to the next lex token after the closing token.

Parameters

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

Return type

List[~N]

delimited_list(delimiter, parse_fn)[source]#

Return a non-empty list of parse nodes determined by parse_fn and separated by a delimiter token of type delimiter Advances the parser to the next lex 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.

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

Return type

List[~N]

parse_document()[source]#

Document : Definition+

Return type

Document

parse_definition()[source]#

Definition : ExecutableDefinition | TypeSystemDefinition

Ignores type system definitions if allow_type_system was set to False.

Return type

Definition

parse_name()[source]#

Convert a name lex token into a name parse node.

Return type

Name

parse_executable_definition()[source]#

ExecutableDefinition : OperationDefinition | FragmentDefinition

Return type

ExecutableDefinition

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_variable_definitions()[source]#

VariableDefinitions : ( VariableDefinition+ )

Returns

Return type

List[py_gql.lang.ast.VariableDefinition]

parse_variable_definition()[source]#

VariableDefinition : Variable : Type DefaultValue?

Return type

VariableDefinition

parse_variable()[source]#

Variable : $ Name

Return type

Variable

parse_selection_set()[source]#

SelectionSet : { Selection+ }

Return type

SelectionSet

parse_selection()[source]#

Selection : Field | FragmentSpread | InlineFragment

Return type

Selection

parse_field()[source]#

Field : Alias? Name Arguments? Directives? SelectionSet?

  • Alias : Name :

Return type

Field

parse_arguments(const=False)[source]#

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

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

List[Argument]

parse_argument(const=False)[source]#

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

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

Argument

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_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”

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

Union[Value, Variable]

parse_list(const=False)[source]#

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

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

ListValue

parse_object(const=False)[source]#

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

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

ObjectValue

parse_object_field(const=False)[source]#

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

Parameters

const (bool) – Whether or not to parse the Const variant

Returns

Return type

py_gql.lang.ast.ObjectField

parse_directives(const=False)[source]#

Directives[Const] : Directive[?Const]+

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

List[Directive]

parse_directive(const=False)[source]#

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

Parameters

const (bool) – Whether or not to parse the Const variant

Return type

Directive

parse_type_reference()[source]#

Type : NamedType | ListType | NonNullType

Return type

Type

parse_named_type()[source]#

NamedType : Name

Return type

NamedType

parse_type_system_definition()[source]#

TypeSystemDefinition : SchemaDefinition | TypeDefinition | TypeExtension | DirectiveDefinition

  • TypeDefinition : ScalarTypeDefinition | ObjectTypeDefinition | InterfaceTypeDefinition | UnionTypeDefinition | EnumTypeDefinition | InputObjectTypeDefinition

Return type

TypeSystemDefinition

parse_description()[source]#

Description : StringValue

Return type

Optional[StringValue]

parse_schema_definition()[source]#

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

Return type

SchemaDefinition

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_object_type_definition()[source]#

ObjectTypeDefinition : Description? type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?

Return type

ObjectTypeDefinition

parse_implements_interfaces()[source]#

ImplementsInterfaces : implements &? NamedType | ImplementsInterfaces & NamedType

Return type

List[NamedType]

parse_fields_definition()[source]#

FieldsDefinition : { FieldDefinition+ }

Return type

List[FieldDefinition]

parse_field_definition()[source]#

FieldDefinition : Description? Name ArgumentsDefinition? : Type Directives[Const]?

Return type

FieldDefinition

parse_argument_definitions()[source]#

ArgumentsDefinition : ( InputValueDefinition+ )

Return type

List[InputValueDefinition]

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_union_type_definition()[source]#

UnionTypeDefinition : Description? union Name Directives[Const]? UnionMemberTypes?

Return type

UnionTypeDefinition

parse_union_member_types()[source]#

UnionMemberTypes : = |? NamedType | UnionMemberTypes | NamedType

Return type

List[NamedType]

parse_enum_type_definition()[source]#

EnumTypeDefinition : Description? enum Name Directives[Const]? EnumValuesDefinition?

Return type

EnumTypeDefinition

parse_enum_values_definition()[source]#

EnumValuesDefinition : { EnumValueDefinition+ }

Return type

List[EnumValueDefinition]

parse_enum_value_definition()[source]#

EnumValueDefinition : Description? EnumValue Directives[Const]?

  • EnumValue : Name

Return type

EnumValueDefinition

parse_input_object_type_definition()[source]#

InputObjectTypeDefinition : Description? input Name Directives[Const]? InputFieldsDefinition?

Return type

InputObjectTypeDefinition

parse_input_fields_definition()[source]#

InputFieldsDefinition : { InputValueDefinition+ }

Return type

List[InputValueDefinition]

parse_type_system_extension()[source]#

TypeSystemExtension : SchemaExtension | TypeExtension

  • TypeExtension : ScalarTypeExtension | ObjectTypeExtension | InterfaceTypeExtension | UnionTypeExtension | EnumTypeExtension | InputObjectTypeDefinition

Return type

TypeSystemExtension

parse_schema_extension()[source]#

SchemaExtension : extend schema Directives[Const] { [OperationTypeDefinition] } | extend schema Directives[Const]

Return type

SchemaExtension

parse_scalar_type_extension()[source]#

ScalarTypeExtension : extend scalar Name Directives[Const]

Return type

ScalarTypeExtension

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_interface_type_extension()[source]#

InterfaceTypeExtension : extend interface Name Directives[Const]? FieldsDefinition | extend interface Name Directives[Const]

Return type

InterfaceTypeExtension

parse_union_type_extension()[source]#

UnionTypeExtension : | extend union Name Directives[Const]? UnionMemberTypes | extend union Name Directives[Const]

Return type

UnionTypeExtension

parse_enum_type_extension()[source]#

EnumTypeExtension : extend enum Name Directives[Const]? EnumValuesDefinition | extend enum Name Directives[Const]

Return type

EnumTypeExtension

parse_input_object_type_extension()[source]#

InputObjectTypeExtension : extend input Name Directives[Const]? InputFieldsDefinition | extend input Name Directives[Const]

Return type

InputObjectTypeExtension

parse_directive_definition()[source]#

DirectiveDefinition : Description? directive @ Name ArgumentsDefinition? on DirectiveLocations

Return type

DirectiveDefinition

parse_directive_locations()[source]#

DirectiveLocations : |? DirectiveLocation | DirectiveLocations | DirectiveLocation

Return type

List[Name]

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

Returns

Return type

py_gql.lang.ast.Name

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 (eg. [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

:raises GraphQLSyntaxError: if a syntax error is encountered.

Return type

Type

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 (eg. [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]

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

Converts an AST node into a valid GraphQL string, using a set of reasonable formatting rules.

Parameters
  • node (py_gql.lanf.ast.Node) – Node to format.

  • indent (Union[str, 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