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)

Convert from CamelCase to snake_case

graphql.pyutils.snake_to_camel(s, upper=True)

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

alias of graphql.pyutils.cached_property.CachedProperty

graphql.pyutils.dedent(text: str) → str

Fix indentation of given text by removing leading spaces and tabs.

Also removes leading newlines and trailing spaces and tabs, but keeps trailing newlines.

graphql.pyutils.did_you_mean(suggestions: Sequence[str], sub_message: Optional[str] = None) → str

Given [ A, B, C ] return ‘ Did you mean A, B, or C?’

class graphql.pyutils.Description

Bases: object

Type checker for human readable descriptions.

By default, only ordinary strings are accepted as descriptions, but you can register() other classes that will also be allowed, e.g. to support lazy string objects that are evaluated only at runtime. If you register(object), any object will be allowed as description.

__init__()

Initialize self. See help(type(self)) for accurate signature.

bases

alias of builtins.str

classmethod isinstance(obj: Any) → bool
classmethod register(base: type) → None

Register a class that shall be accepted as a description.

classmethod unregister(base: type) → None

Unregister a class that shall no more be accepted as a description.

graphql.pyutils.is_description(obj: Any) → bool
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.

class graphql.pyutils.EventEmitter(loop: Optional[asyncio.events.AbstractEventLoop] = None)

Bases: object

A very simple EventEmitter.

__init__(loop: Optional[asyncio.events.AbstractEventLoop] = None)

Initialize self. See help(type(self)) for accurate signature.

add_listener(event_name: str, listener: Callable)

Add a listener.

emit(event_name, *args, **kwargs)

Emit an event.

remove_listener(event_name, listener)

Removes a listener.

class graphql.pyutils.EventEmitterAsyncIterator(event_emitter: graphql.pyutils.event_emitter.EventEmitter, event_name: str)

Bases: object

Create an AsyncIterator from an EventEmitter.

Useful for mocking a PubSub system for tests.

__init__(event_emitter: graphql.pyutils.event_emitter.EventEmitter, event_name: str)

Initialize self. See help(type(self)) for accurate signature.

async aclose()
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_collection(value: Any) → bool

Check if value is a collection, but not a mapping and not a string.

graphql.pyutils.is_finite(value: Any) → bool

Return true if a value is a finite number.

graphql.pyutils.is_integer(value: Any) → bool

Return true if a value is an integer number.

graphql.pyutils.is_invalid(value: Any) → bool

Return true if a value is undefined, or NaN.

graphql.pyutils.is_nullish(value: Any) → bool

Return true if a value is null, undefined, or NaN.

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.

exception graphql.pyutils.FrozenError

Bases: TypeError

Error when trying to change a frozen (read only) collection.

__init__()

Initialize self. See help(type(self)) for accurate signature.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class graphql.pyutils.FrozenList

Bases: list, typing.Generic

List that can only be read, but not changed.

__init__()

Initialize self. See help(type(self)) for accurate signature.

append(x)

Append object to the end of the list.

clear()

Remove all items from list.

copy()

Return a shallow copy of the list.

count()

Return number of occurrences of value.

extend(iterable)

Extend list by appending elements from the iterable.

index()

Return first index of value.

Raises ValueError if the value is not present.

insert(i, x)

Insert object before index.

pop(i=None)

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

remove(x)

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse()

Reverse IN PLACE.

sort(*, key=None, reverse=False)

Stable sort IN PLACE.

class graphql.pyutils.FrozenDict

Bases: dict, typing.Generic

Dictionary that can only be read, but not changed.

__init__()

Initialize self. See help(type(self)) for accurate signature.

clear() → None. Remove all items from D.
copy()
fromkeys()

Create a new dictionary with keys from iterable and values set to value.

get()

Return the value for key if key is in the dictionary, else default.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) → None. Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() → an object providing a view on D's values
class graphql.pyutils.Path

Bases: tuple

A generic path of string or integer indices

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'key': typing.Union[str, int], 'prev': typing.Any}
_fields = ('prev', 'key')
_fields_defaults = {}
classmethod _make(iterable)

Make a new Path object from a sequence or iterable

_replace(**kwds)

Return a new Path object replacing specified fields with new values

add_key(key: Union[str, int]) → graphql.pyutils.path.Path

Return a new Path containing the given key.

as_list() → List[Union[str, int]]

Return a list of the path keys.

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

property key

current index in the path (string or integer)

property prev

path with the previous indices

graphql.pyutils.print_path_list(path: Collection[Union[str, int]])

Build a string describing the path.

exception graphql.pyutils.UndefinedType

Bases: ValueError

Auxiliary class for creating the Undefined singleton.

__init__()

Initialize self. See help(type(self)) for accurate signature.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

graphql.pyutils.camel_to_snake(s)

Convert from CamelCase to snake_case

graphql.pyutils.snake_to_camel(s, upper=True)

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)

A cached property.

A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property.

graphql.pyutils.dedent(text: str) → str

Fix indentation of given text by removing leading spaces and tabs.

Also removes leading newlines and trailing spaces and tabs, but keeps trailing newlines.

graphql.pyutils.did_you_mean(suggestions: Sequence[str], sub_message: Optional[str] = None) → str

Given [ A, B, C ] return ‘ Did you mean A, B, or C?’

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.

class graphql.pyutils.EventEmitter(loop: Optional[asyncio.events.AbstractEventLoop] = None)

Bases: object

A very simple EventEmitter.

__init__(loop: Optional[asyncio.events.AbstractEventLoop] = None)

Initialize self. See help(type(self)) for accurate signature.

add_listener(event_name: str, listener: Callable)

Add a listener.

emit(event_name, *args, **kwargs)

Emit an event.

remove_listener(event_name, listener)

Removes a listener.

class graphql.pyutils.EventEmitterAsyncIterator(event_emitter: graphql.pyutils.event_emitter.EventEmitter, event_name: str)

Bases: object

Create an AsyncIterator from an EventEmitter.

Useful for mocking a PubSub system for tests.

__init__(event_emitter: graphql.pyutils.event_emitter.EventEmitter, event_name: str)

Initialize self. See help(type(self)) for accurate signature.

async aclose()
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_finite(value: Any) → bool

Return true if a value is a finite number.

graphql.pyutils.is_integer(value: Any) → bool

Return true if a value is an integer number.

graphql.pyutils.is_invalid(value: Any) → bool

Return true if a value is undefined, or NaN.

graphql.pyutils.is_nullish(value: Any) → bool

Return true if a value is null, undefined, or NaN.

graphql.pyutils.AwaitableOrValue
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: TypeError

Error when trying to change a frozen (read only) collection.

__init__()

Initialize self. See help(type(self)) for accurate signature.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class graphql.pyutils.FrozenList

Bases: list, typing.Generic

List that can only be read, but not changed.

__init__()

Initialize self. See help(type(self)) for accurate signature.

append(x)

Append object to the end of the list.

clear()

Remove all items from list.

copy()

Return a shallow copy of the list.

count()

Return number of occurrences of value.

extend(iterable)

Extend list by appending elements from the iterable.

index()

Return first index of value.

Raises ValueError if the value is not present.

insert(i, x)

Insert object before index.

pop(i=None)

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

remove(x)

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse()

Reverse IN PLACE.

sort(*, key=None, reverse=False)

Stable sort IN PLACE.

class graphql.pyutils.FrozenDict

Bases: dict, typing.Generic

Dictionary that can only be read, but not changed.

__init__()

Initialize self. See help(type(self)) for accurate signature.

clear() → None. Remove all items from D.
copy()
fromkeys()

Create a new dictionary with keys from iterable and values set to value.

get()

Return the value for key if key is in the dictionary, else default.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) → None. Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() → an object providing a view on D's values
class graphql.pyutils.Path

Bases: tuple

A generic path of string or integer indices

__init__()

Initialize self. See help(type(self)) for accurate signature.

_asdict()

Return a new OrderedDict which maps field names to their values.

_field_defaults = {}
_field_types = {'key': typing.Union[str, int], 'prev': typing.Any}
_fields = ('prev', 'key')
_fields_defaults = {}
classmethod _make(iterable)

Make a new Path object from a sequence or iterable

_replace(**kwds)

Return a new Path object replacing specified fields with new values

add_key(key: Union[str, int]) → graphql.pyutils.path.Path

Return a new Path containing the given key.

as_list() → List[Union[str, int]]

Return a list of the path keys.

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

property key

current index in the path (string or integer)

property prev

path with the previous indices

graphql.pyutils.print_path_list(path: Collection[Union[str, int]])

Build a string describing the path.

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 undefined in GraphQL.js.