Skip to content

Utilities API

general_manager.utils.none_to_zero.none_to_zero

none_to_zero(value)

Return 0 for None and otherwise return the original numeric value.

The helper does not coerce, copy, or normalize non-None values. Existing int, float, and Measurement inputs are returned unchanged, so falsey numeric values such as 0 or 0.0 remain their original values.

Parameters:

Name Type Description Default
value NumberValue | None

Numeric value or Measurement instance that may be None.

required

Returns:

Type Description
NumberValue | Literal[0]

The original value when it is not None; otherwise the integer

NumberValue | Literal[0]

literal 0.

none_to_zero(value) returns the integer 0 only when value is None. Non-None int, float, and Measurement values are returned unchanged, without copying or coercion, so existing falsey numeric values such as 0 and 0.0 remain the original values.

general_manager.utils.args_to_kwargs.args_to_kwargs

args_to_kwargs(args, keys, existing_kwargs=None)

Map positional arguments to the given keys and merge the result with an optional existing kwargs mapping.

The keys iterable is materialized once, then paired with args in order. Supplying fewer positional values than keys leaves the remaining keys absent. existing_kwargs is merged after generated values, including falsey custom mapping objects; any overlapping key raises before merging. The returned dictionary is new: generated key order comes first, followed by the iteration order of existing_kwargs for non-conflicting keys. existing_kwargs itself is not mutated.

Parameters:

Name Type Description Default
args tuple[object, ...]

Positional values to assign to keys in order.

required
keys Iterable[str]

Keys to assign positional values to. Duplicate keys are allowed and follow normal dictionary overwrite semantics while generated positional values are built.

required
existing_kwargs Mapping[str, object] | None

Optional keyword mapping to merge into the result. None means no existing keywords; falsey mapping objects are still inspected and merged.

None

Returns:

Type Description
dict[str, object]

dict[str, object]: A new dictionary containing the mapped keys for the provided positional arguments plus all entries from existing_kwargs (if given).

Raises:

Type Description
TooManyArgumentsError

If more positional arguments are provided than keys.

ConflictingKeywordError

If existing_kwargs contains a key that was already produced from args and keys.

Exception

Exceptions raised while iterating keys, iterating existing_kwargs, or reading keys/values from existing_kwargs propagate unchanged.

args_to_kwargs(args, keys, existing_kwargs=None) materializes keys once, maps positional values to those keys in order, and merges existing_kwargs afterward. Fewer positional values than keys leave the remaining keys absent. Duplicate generated keys follow normal dictionary overwrite behavior while the positional mapping is built, so the later paired value wins. existing_kwargs is inspected and merged whenever it is not None, including falsey custom mapping objects; overlap with generated keys raises ConflictingKeywordError before merging. More positional values than keys raises TooManyArgumentsError. Errors from iterating keys or existing_kwargs and errors from reading keys or values from existing_kwargs propagate unchanged. The returned dictionary is new and preserves insertion order as generated keys first, then non-conflicting entries from existing_kwargs; existing_kwargs itself is not mutated.

general_manager.conf.get_setting

get_setting(key: str) -> object | None
get_setting(key: str, default: _T) -> object | _T
get_setting(key, default=None)

Look up a GeneralManager configuration value.

Resolution order: 1. settings.GENERAL_MANAGER[key], when GENERAL_MANAGER is a dict 2. settings.GENERAL_MANAGER_<key> legacy prefixed setting 3. settings.<key> legacy top-level setting 4. default

Non-dict GENERAL_MANAGER values are ignored. Attribute-access errors from Django settings are not wrapped.

get_setting(key, default=None) resolves GeneralManager settings from nested settings.GENERAL_MANAGER[key], then legacy settings.GENERAL_MANAGER_<key>, then legacy top-level settings.<key>, then default. Only dict-valued GENERAL_MANAGER settings are considered nested config; other values are ignored. A nested value of None is returned as configured. Unexpected settings attribute errors are not wrapped.

general_manager.utils.make_cache_key.make_cache_key

make_cache_key(func, args, kwargs)

Build a deterministic cache key for one function invocation.

kwargs=None is treated as an empty mapping; supplied mappings are copied with dict(...) even when they are falsey. The function module, qualified name, and normalized bound arguments are encoded as JSON with sorted keys and CustomJSONEncoder, then hashed with SHA-256 using usedforsecurity=False. An active historical snapshot adds its ISO datetime as an as_of payload field; current payload bytes remain unchanged. Positional and keyword forms of the same call produce the same key after inspect.Signature.bind_partial() and default application.

Raises:

Type Description
TypeError

If args and kwargs cannot bind to func's signature, or if payload serialization fails before CustomJSONEncoder can fall back to strings.

make_cache_key(func, args, kwargs) treats kwargs=None as empty kwargs and copies supplied mappings with dict(...), including falsey custom mappings. It binds arguments with inspect.Signature.bind_partial(), applies default values, serializes the function module, qualified name, and bound arguments with sorted JSON keys using CustomJSONEncoder, then returns a SHA-256 hex digest computed with usedforsecurity=False. Invalid argument combinations raise TypeError from signature binding. Serialization errors from the custom encoder can propagate.

general_manager.utils.filter_parser.UnknownInputFieldError

Bases: ValueError

Raised when a filter references an unknown input field.

__init__

__init__(field_name)

Build an error for the unknown filter field name.

Parameters:

Name Type Description Default
field_name str

Field name parsed from the filter key.

required

Attributes:

Name Type Description
field_name

The unknown field name parsed from the filter key.

general_manager.utils.filter_parser.parse_filters

parse_filters(filter_kwargs, possible_values)

Parse raw filter keyword arguments into bucket or Python filter criteria.

filter_kwargs uses Django-style keys of field or field__lookup. Inputs whose type is a :class:general_manager.GeneralManager subclass are returned as filter_kwargs for downstream bucket filtering. The lookup suffix is preserved for manager inputs, so project__name__startswith becomes a manager criterion with lookup name__startswith. All other inputs are always returned as filter_funcs predicates produced by :func:create_filter_function; non-manager inputs never emit filter_kwargs.

Manager input aliases ending in _id are accepted when the alias without _id is a configured manager input. The alias is translated to an id lookup, so project_id__in=[1, 2] becomes {"id__in": [1, 2]}. Alias values are passed through unchanged because the alias already targets the downstream id lookup. For manager inputs, any suffix after the field name is an explicit downstream lookup path, whether or not its final segment is one of the predicate lookup names. Such suffixes preserve the raw value unchanged for downstream bucket filtering. A direct manager filter without a suffix, such as project=raw_value, is cast through the manager Input when the value is not already a manager instance. Values that are already GeneralManager instances skip casting. In both cases the final downstream value is getattr(value, "id", value).

Non-manager list and tuple values are cast element-by-element when they are not already instances of the configured input type; other non-manager values are cast once. Multiple criteria for the same field are appended in the iteration order produced by filter_kwargs.items(). Manager filter kwargs are stored in a mapping, so normalized duplicate lookup keys for the same field overwrite earlier values; for example project_id__in and project__id__in both normalize to id__in and the later item wins. Non-manager duplicate criteria append another predicate. Empty criteria entries are not emitted. Input.cast conversion behavior follows the public Input contract documented in the core API reference.

Parameters:

Name Type Description Default
filter_kwargs Mapping[str, object]

Raw filter expressions keyed by field or field__lookup.

required
possible_values InputFieldMap

Mapping of valid input field names to Input definitions used for type detection and value casting.

required

Returns:

Type Description
ParsedFilters

A mapping by input field. Each entry contains filter_kwargs for

ParsedFilters

manager inputs or filter_funcs for non-manager inputs.

Raises:

Type Description
UnknownInputFieldError

If a filter references a field that is not in possible_values and is not a valid manager _id alias.

ValueError

Propagated from Input.cast when a value cannot be converted.

TypeError

Propagated from input type checks or custom casts.

general_manager.utils.filter_parser.create_filter_function

create_filter_function(lookup_str, value)

Build a predicate for an optional attribute path and lookup operation.

lookup_str may be a lookup name such as gte or a nested attribute path such as address__city__exact. If the final path segment is not a supported lookup, the whole string is treated as an attribute path and the lookup defaults to exact. Attribute traversal uses getattr only; it does not read mapping keys or sequence indexes. Missing attributes return False. Empty path segments are treated as literal attribute names, so malformed strings generally return False instead of raising.

Parameters:

Name Type Description Default
lookup_str str

Attribute path and optional lookup operator separated by double underscores.

required
value object

Reference value used by the lookup comparison.

required

Returns:

Type Description
FilterFunction

A predicate returning True when the target object or nested

FilterFunction

attribute satisfies the lookup.

general_manager.utils.format_string.snake_to_pascal

snake_to_pascal(s)

Convert a snake_case string to PascalCase.

The function splits only on underscores and title-cases each segment. Empty segments from leading, trailing, or repeated underscores disappear. Digits and non-underscore punctuation are preserved by str.title(). Acronyms are not preserved; each segment follows Python's title-casing rules.

Parameters:

Name Type Description Default
s str

Input string to convert.

required

Returns:

Type Description
str

The converted string. Empty input returns an empty string.

general_manager.utils.format_string.snake_to_camel

snake_to_camel(s)

Convert a snake_case string to camelCase.

The first underscore-delimited segment is returned unchanged. Later segments are title-cased and concatenated. Empty later segments disappear, so repeated or trailing underscores are collapsed. A leading underscore makes the first segment empty, so the first non-empty segment is title-cased.

Parameters:

Name Type Description Default
s str

Input string to convert.

required

Returns:

Type Description
str

The converted string. Empty input returns an empty string.

general_manager.utils.format_string.pascal_to_snake

pascal_to_snake(s)

Convert a PascalCase string to snake_case.

Every uppercase character is lower-cased and prefixed with an underscore, then all leading underscores are stripped from the final result. Consecutive uppercase characters are therefore split one character at a time ("ABC" becomes "a_b_c"). Existing underscores that are not at the front are preserved, as are digits, lowercase characters, and other punctuation.

Parameters:

Name Type Description Default
s str

Input string to convert.

required

Returns:

Type Description
str

The converted string. Empty input returns an empty string.

general_manager.utils.format_string.camel_to_snake

camel_to_snake(s)

Convert a camelCase string to snake_case.

The first character is lower-cased. Every later uppercase character is lower-cased and prefixed with an underscore. Consecutive uppercase characters are split one character at a time, and existing underscores, digits, lowercase characters, and punctuation are preserved.

Parameters:

Name Type Description Default
s str

Input string to convert.

required

Returns:

Type Description
str

The converted string. Empty input returns an empty string.

The casing helpers are simple string transforms used by GeneralManager's public GraphQL and Python naming layers. snake_to_pascal() splits only on underscores, title-cases every segment, and drops empty segments from leading, trailing, or repeated underscores. snake_to_camel() keeps the first underscore-delimited segment unchanged and title-cases later segments. The reverse helpers lower-case uppercase characters one character at a time and prefix them with underscores after the first character, so acronym-like runs are not preserved as words ("ABC" becomes "a_b_c"). Digits, lowercase characters, existing underscores, and non-underscore punctuation are preserved unless Python str.title() changes a segment during the snake-case helpers. Empty input returns an empty string.

general_manager.utils.json_encoder.CustomJSONEncoder

Bases: JSONEncoder

JSON encoder for values commonly found in GeneralManager payloads.

Dates, datetimes, and times are emitted with isoformat(). Current GeneralManager instances are represented as <ClassName>(**<identification>); snapshot-bound instances append an @as_of(<isoformat>) suffix. Values supported by the standard JSON encoder keep the normal json.JSONEncoder behavior. Unsupported values fall back to str(value) instead of raising TypeError.

default

default(o)

Return a JSON-compatible value for o.

Raises:

Type Description
Exception

Errors raised by isoformat(), GeneralManager.identification, or str(o) are allowed to propagate.

CustomJSONEncoder preserves standard JSON encoding, serializes date/time objects with isoformat(), formats GeneralManager instances as ClassName(**identification), and falls back to str(value) for otherwise unsupported objects. Exceptions from identification access or str(value) propagate.

general_manager.utils.path_mapping.PathMap

Maintain cached traversal paths between GeneralManager classes.

The class-level mapping stores lazily resolved PathTracer objects for requested start/destination class-name pairs. A cached tracer may have path is None when the classes are known but no route exists.

__new__

__new__(*args, **kwargs)

Obtain the singleton PathMap, refreshing graph metadata on each construction.

Returns:

Name Type Description
PathMap PathMap

The singleton PathMap instance.

create_path_mapping classmethod

create_path_mapping()

Refresh path graph metadata without eagerly creating all pair tracers.

Returns:

Type Description
None

None

__init__

__init__(path_start)

Create a new traversal context rooted at the provided manager class or instance.

Parameters:

Name Type Description Default
path_start PathStart | GeneralManager | type[GeneralManager]

Manager class name, manager instance, or manager class that serves as the origin for future path lookups. Only an instance can be traversed with go_to.

required

Returns:

Type Description
None

None

to

to(path_destination)

Retrieve the cached path tracer from the start class to the desired destination.

None means either the start or destination class name is not registered, or the requested pair uses the same start and destination class. A non-None tracer can still be unreachable; inspect tracer.path for None before treating it as a usable route.

Parameters:

Name Type Description Default
path_destination PathDestination | type[GeneralManager] | str

Target manager identifier, either as a manager class or string class name. Destination instances are not accepted.

required

Returns:

Type Description
PathTracer | None

PathTracer | None: The cached tracer for the registered class-name pair, or None when no mapping key can be created.

go_to

go_to(path_destination)

Traverse the cached path from the configured start to the given destination.

The lookup lazily resolves and caches the requested tracer. Missing tracer keys and tracers with path is None return None. A tracer with an empty path also returns None because no traversal is required. If a traversable path exists but this PathMap was created from a class or string start, MissingStartInstanceError is raised.

Parameters:

Name Type Description Default
path_destination PathDestination | type[GeneralManager] | str

Destination specified as a manager class or string class name. Destination instances are not accepted.

required

Returns:

Type Description
TraversalValue | None

GeneralManager | Bucket[GeneralManager] | None: The resolved GeneralManager instance, a Bucket of instances reached by the path, or None if no cached path exists.

Raises:

Type Description
MissingStartInstanceError

If the cached path requires a concrete start instance but the PathMap was constructed without one.

get_all_connected

get_all_connected()

Return the set of destination class names reachable from the configured start.

Returns:

Type Description
set[str]

set[str]: Destination class names reachable from the current start_class_name.

general_manager.utils.path_mapping.PathTracer

Resolve attribute paths linking one manager class to another.

The public path attribute is [] for the same start/destination class, a list of attribute names for the first discovered route, or None when no route exists.

__init__

__init__(
    start_class,
    destination_class,
    path=None,
    *,
    search=True
)

Initialise a path tracer between two manager classes.

Parameters:

Name Type Description Default
start_class type[GeneralManager]

Origin manager class where traversal begins.

required
destination_class type[GeneralManager]

Target manager class to reach.

required
path list[str] | None

Precomputed path used by lazy PathMap lookup when search is False.

None
search bool

Whether to compute the path during construction.

True

Returns:

Type Description
None

None

create_path

create_path(current_manager, path, visited_managers=None)

Recursively compute the traversal path from current_manager to the destination class.

Candidate edges come from Interface.get_attribute_types() entries that expose a type key and from @GraphQLProperty return annotations. Only GeneralManager subclasses are traversed. Each manager class is expanded at most once, which bounds missing-path and cyclic graph searches.

Parameters:

Name Type Description Default
current_manager type[GeneralManager]

Manager class used as the current traversal node.

required
path list[str]

Sequence of attribute names accumulated along the traversal.

required
visited_managers set[type[GeneralManager]] | None

Manager classes already expanded during this search.

None

Returns:

Type Description
list[str] | None

list[str] | None: Updated list of attribute names leading to the destination, or None if no route exists.

traverse_path

traverse_path(start_instance)

Traverse the stored path starting from the provided manager or bucket instance.

Manager traversal reads the next path attribute directly. Bucket traversal reads the attribute from each bucket entry and unions the resulting manager or bucket values. None is returned for no path, same-class empty paths, and empty buckets. Every resolved attribute must be a GeneralManager or Bucket.

Parameters:

Name Type Description Default
start_instance GeneralManager | Bucket[GeneralManager]

Object used as the traversal root.

required

Returns:

Type Description
TraversalValue | None

GeneralManager | Bucket[GeneralManager] | None: The resolved destination object, a merged bucket, or None when no traversal is required.

Raises:

Type Description
InvalidPathTraversalValueError

If a traversed attribute resolves to neither a GeneralManager nor a Bucket.

general_manager.utils.path_mapping.MissingStartInstanceError

Bases: ValueError

Raised when attempting to traverse a path without a starting instance.

__init__

__init__()

Create the MissingStartInstanceError with its default message.

This initializer constructs the exception with the message: "Cannot call go_to on a PathMap without a start instance."

general_manager.utils.path_mapping.InvalidPathTraversalValueError

Bases: TypeError

Raised when a traced path attribute does not return a traversable value.