PyUtils
Python Utils
This package contains dependency-free Python utility functions used throughout the codebase.
Each utility should belong in its own file and be the default export.
These functions are not part of the module interface and are subject to change.
- graphql.pyutils.camel_to_snake(s: str) str
Convert from CamelCase to snake_case
- graphql.pyutils.snake_to_camel(s: str, upper: bool = True) str
Convert from snake_case to CamelCase
If upper is set, then convert to upper CamelCase, otherwise the first character keeps its case.
- graphql.pyutils.cached_property(func)
- graphql.pyutils.register_description(base: type) None
Register a class that shall be accepted as a description.
- graphql.pyutils.unregister_description(base: type) None
Unregister a class that shall no more be accepted as a description.
- graphql.pyutils.did_you_mean(suggestions: Sequence[str], sub_message: str | None = None) str
Given [ A, B, C ] return ‘ Did you mean A, B, or C?’
- graphql.pyutils.identity_func(x: T = Undefined, *_args: Any) T
Return the first received argument.
- graphql.pyutils.inspect(value: Any) str
Inspect value and a return string representation for error messages.
Used to print values in error messages. We do not use repr() in order to not leak too much of the inner Python representation of unknown objects, and we do not use json.dumps() because not all objects can be serialized as JSON and we want to output strings with single quotes like Python repr() does it.
We also restrict the size of the representation by truncating strings and collections and allowing only a maximum recursion depth.
- graphql.pyutils.is_awaitable(value: Any) TypeGuard[Awaitable]
Return True if object can be passed to an
awaitexpression.Instead of testing whether the object is an instance of abc.Awaitable, we check the existence of an __await__ attribute. This is much faster.
- graphql.pyutils.is_async_iterable(value: Any) TypeGuard[AsyncIterable]
Return True if object is an asynchronous iterable.
Instead of testing whether the object is an instance of abc.AsyncIterable, we check the existence of an __aiter__ attribute. This is much faster.
- graphql.pyutils.is_collection(value: Any) TypeGuard[Collection]
Check if value is a collection, but not a string or a mapping.
- graphql.pyutils.is_iterable(value: Any) TypeGuard[Iterable]
Check if value is an iterable, but not a string or a mapping.
- graphql.pyutils.natural_comparison_key(key: str) tuple
Comparison key function for sorting strings by natural sort order.
- class graphql.pyutils.AbortController
Bases:
objectA controller object for aborting the execution of a GraphQL operation.
This mirrors the JavaScript
AbortControllerWeb API. Pass itssignalas theabort_signalargument toexecute(and related functions) and callabort()to cancel the execution.>>> from graphql.pyutils import AbortController >>> controller = AbortController() >>> controller.signal.aborted False >>> controller.abort() >>> controller.signal.aborted True >>> controller.signal.reason AbortError('This operation was aborted')
- abort(reason: Any = None) None
Abort the operation, optionally specifying a reason.
The reason becomes the resulting GraphQL error: an exception is used as its original error, while any other value is wrapped by
located_erroras an “Unexpected error value”. If no reason is given, anAbortErrorwith a generic message is used. Aborting more than once has no further effect.- Parameters:
reason – the reason for aborting, by default an
AbortError
>>> from graphql.pyutils import AbortController >>> controller = AbortController() >>> controller.abort(RuntimeError('Cancelled by user')) >>> controller.abort(RuntimeError('Ignored')) >>> controller.signal.reason RuntimeError('Cancelled by user')
- signal: AbortSignal
The signal controlled by this controller.
- class graphql.pyutils.AbortSignal
Bases:
objectA signal object that communicates an abort request to the executor.
This mirrors the JavaScript
AbortSignalWeb API. The executor only ever inspects the synchronousabortedflag (andreason) at field boundaries, so any object exposing these two attributes can be used in place of this class. In addition to that pollable interface, this implementation is also awaitable viawait(), allowing resolvers to react to an abort of a running operation immediately instead of only at the next field boundary.The signal is created and controlled through an
AbortController.>>> from graphql.pyutils import AbortController >>> signal = AbortController().signal >>> signal.aborted, signal.reason (False, None)
- aborted: bool
Whether the operation has been aborted.
- reason: Any
The reason given when aborting, or None if not aborted yet.
- async wait() Any
Wait until the signal is aborted and return the abort reason.
- Returns:
the abort reason
>>> import asyncio >>> from graphql.pyutils import AbortController >>> async def main(): ... controller = AbortController() ... asyncio.get_running_loop().call_soon(controller.abort, 'timeout') ... return await controller.signal.wait() >>> asyncio.run(main()) 'timeout'
- exception graphql.pyutils.AbortError
Bases:
ExceptionError used as the default reason when an operation is aborted.
This is the Python counterpart of the
AbortErrorDOMExceptionthat the JavaScriptAbortController.abort()uses when called without a reason.- add_note(note, /)
Add a note to the exception
- args
- with_traceback(tb, /)
Set self.__traceback__ to tb and return self.
- graphql.pyutils.AwaitableOrValue
alias of
Awaitable[T] |T
- graphql.pyutils.suggestion_list(input_: str, options: Collection[str]) list[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.
- class graphql.pyutils.FrozenError
Bases:
TypeErrorError when trying to change a frozen (read only) collection.
- class graphql.pyutils.Path(prev: Path | None, key: str | int, typename: str | None)
Bases:
NamedTupleA generic path of string or integer indices.
Represents a linked response path from a field back to the root response.
- add_key(key: str | int, typename: str | None = None) Path
Return a new Path containing the given key.
- Parameters:
key – the field name or list index of the new path segment
typename – the runtime object type name of the new path segment, if known
- Returns:
a new path with this path as its previous segment
>>> from graphql.pyutils import Path >>> path = Path(None, 'viewer', 'Query').add_key('friends', 'User') >>> path.key, path.typename, path.prev.key ('friends', 'User', 'viewer')
- as_list() list[str | int]
Return a list of the path keys.
- Returns:
a list of response path keys from root to leaf
>>> from graphql.pyutils import Path >>> path = Path(None, 'viewer', 'Query').add_key('friends', 'User').add_key(0) >>> path.as_list() ['viewer', 'friends', 0]
- count(value, /)
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- key: str | int
The field name or list index for this response path segment.
- typename: str | None
The runtime object type name associated with this path segment, if known.
- graphql.pyutils.print_path_list(path: Collection[str | int]) str
Build a string describing the path.
- class graphql.pyutils.SimplePubSub
Bases:
objectA very simple publish-subscript system.
Creates an AsyncIterator from an EventEmitter.
Useful for mocking a PubSub system for tests.
- emit(event: Any) bool
Emit an event.
- get_subscriber(transform: Callable | None = None) SimplePubSubIterator
Return subscriber iterator
- subscribers: set[Callable]
- class graphql.pyutils.SimplePubSubIterator(pubsub: SimplePubSub, transform: Callable | None)
Bases:
AsyncIteratorAsync iterator used for subscriptions.
- async aclose() None
Close the iterator.
- async empty_queue() None
Empty the queue.
- pull_queue: Queue[Future]
- push_queue: Queue[Any]
- async push_value(event: Any) None
Push a new value.
- graphql.pyutils.Undefined = Undefined
Symbol for undefined values
This singleton object is used to describe undefined or invalid values. It can be used in places where you would use
undefinedin GraphQL.js.
- class graphql.pyutils.RefMap(items: Iterable[tuple[K, V]] | None = None)
Bases:
MutableMapping[K,V]A dictionary like object that allows mutable objects as keys.
This class keeps the insertion order like a normal dictionary.
Note that the implementation is limited to what is needed internally.
- get(key: Any, default: Any = None) Any
Get the mapped value for the given key.
- items() Iterator[tuple[K, V]]
Return an iterator over the key/value-pairs of the map.
- keys() Iterator[K]
Return an iterator over the keys of the map.
- update(items: Iterable[tuple[K, V]] | None = None) None
Update the map with the given key/value-pairs.
- values() Iterator[V]
Return an iterator over the values of the map.
- class graphql.pyutils.RefSet(values: Iterable[T] | None = None)
Bases:
MutableSet[T]A set like object that allows mutable objects as elements.
This class keeps the insertion order unlike a normal set.
Note that the implementation is limited to what is needed internally.
- add(value: T) None
Add the given item to the set.
- discard(value: T) None
Remove the given item from the set if it exists.
- remove(value: T) None
Remove the given item from the set.
- update(values: Iterable[T] | None = None) None
Update the set with the given items.
- class graphql.pyutils.SetMap(items: Iterable[tuple[S, V]] | None = None)
Bases:
MutableMapping[S,V]Map an order-independent set of member identities to a value.
Unlike a
RefMapkeyed by sets, two sets containing the same members address the same entry even when they are different set objects.Members are compared by identity, so they do not need to be hashable. The key of an entry is the frozen set of the identities of its members. Since every stored set keeps its members alive, these identities cannot be reused while the entry exists.
Iteration follows insertion order and returns the first set object stored for each key. Key sets must not be mutated after insertion.
Note that the implementation is limited to what is needed internally.
- get(members: S, default: Any = None) Any
Get the value mapped to the given set of members.
- get_or_insert(members: S, value: V) V
Get the mapped value, inserting the given value if there is none.
- get_or_insert_computed(members: S, compute_value: Callable[[S], V]) V
Get the mapped value, inserting a computed value if there is none.
- items() Iterator[tuple[S, V]]
Return an iterator over the key/value-pairs of the map.
- keys() Iterator[S]
Return an iterator over the canonical key sets of the map.
- values() Iterator[V]
Return an iterator over the values of the map.