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.
AwaitableOrValue
¶ alias of Union[Awaitable[T], T]
-
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.
-
-
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
()¶
-
-
class
graphql.pyutils.
FrozenDict
¶ Bases:
dict
,typing.Generic
Dictionary that can only be read, but not changed.
-
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.
-
_is_protocol
¶
-
clear
() → None. Remove all items from D.¶
-
copy
() → a shallow copy of D¶
-
fromkeys
(value=None, /)¶ Create a new dictionary with keys from iterable and values set to value.
-
get
(key, default=None, /)¶ 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, default is returned if given, otherwise KeyError is raised
-
popitem
()¶ Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict 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¶
-
-
exception
graphql.pyutils.
FrozenError
¶ Bases:
TypeError
Error when trying to change a frozen (read only) collection.
-
__init__
(*args, **kwargs)¶ 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
(iterable=(), /)¶ Bases:
list
,typing.Generic
List that can only be read, but not changed.
-
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.
-
_is_protocol
¶
-
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
(value, /)¶ Return number of occurrences of value.
-
extend
(iterable)¶ Extend list by appending elements from the iterable.
-
index
(value, start=0, stop=9223372036854775807, /)¶ 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)¶ Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
-
-
class
graphql.pyutils.
Path
(prev: Any, key: Union[str, int])¶ Bases:
tuple
A generic path of string or integer indices
-
__init__
()¶ Initialize self. See help(type(self)) for accurate signature.
-
_asdict
()¶ Return a new dict which maps field names to their values.
-
_field_defaults
¶
-
_fields
¶
-
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
(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
¶ current index in the path (string or integer)
-
prev
¶ path with the previous indices
-
-
exception
graphql.pyutils.
UndefinedType
¶ Bases:
ValueError
Auxiliary class for creating the Undefined singleton.
-
__init__
(*args, **kwargs)¶ 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.
cached_property
(func)¶ Bases:
object
-
__init__
(func)¶ Initialize self. See help(type(self)) for accurate signature.
-
-
graphql.pyutils.
camel_to_snake
(s)¶ Convert from CamelCase to snake_case
-
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.
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) → bool¶ Return true if object can be passed to an
await
expression.Instead of testing if the object is an instance of abc.Awaitable, it checks the existence of an __await__ attribute. This is much faster.
-
graphql.pyutils.
is_collection
(value: Any) → bool¶ Check if value is a collection, but not a mapping and not a string.
-
graphql.pyutils.
is_description
(obj: Any) → bool¶
-
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.
print_path_list
(path: Collection[Union[str, int]])¶ Build a string describing the path.
-
graphql.pyutils.
register_description
(base: type) → None¶ Register a class that shall be accepted as a description.
-
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.
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.
-
graphql.pyutils.
unregister_description
(base: type) → None¶ Unregister a class that shall no more be accepted as a description.
-
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)¶
-
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.
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__
(*args, **kwargs)¶ 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
(iterable=(), /)¶ Bases:
list
,typing.Generic
List that can only be read, but not changed.
-
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.
-
_is_protocol
= False¶
-
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
(value, /)¶ Return number of occurrences of value.
-
extend
(iterable)¶ Extend list by appending elements from the iterable.
-
index
(value, start=0, stop=9223372036854775807, /)¶ 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)¶ Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
-
-
class
graphql.pyutils.
FrozenDict
¶ Bases:
dict
,typing.Generic
Dictionary that can only be read, but not changed.
-
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.
-
_is_protocol
= False¶
-
clear
() → None. Remove all items from D.¶
-
copy
() → a shallow copy of D¶
-
fromkeys
(value=None, /)¶ Create a new dictionary with keys from iterable and values set to value.
-
get
(key, default=None, /)¶ 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, default is returned if given, otherwise KeyError is raised
-
popitem
()¶ Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict 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
(prev: Any, key: Union[str, int])¶ Bases:
tuple
A generic path of string or integer indices
-
__init__
()¶ Initialize self. See help(type(self)) for accurate signature.
-
_asdict
()¶ Return a new dict which maps field names to their values.
-
_field_defaults
= {}¶
-
_fields
= ('prev', 'key')¶
-
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
(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
: Union[str, int]¶ current index in the path (string or integer)
-
prev
: Any¶ 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.