stratified_packager.toolbelt.mapping_proxy
QGIS-free foundation for the typed key/value proxies: conversions, mapping base, environment.
This module holds the parts of the persistence layer that touch no QGIS objects, so it is importable (and thread-safe) without a QGIS runtime:
a small type-conversion registry (
register_converter(),to_storage(),from_storage()) that round-trips Python values to and from the scalar representations every backend can persist;MappingProxy, the abstractMutableMappingbase that the concrete proxies subclass, providing consistent[]/in/len/iteration semantics plus a typedget(); andEnvironmentVariables+ theEnvVardescriptors — a concreteMappingProxyoveros.environ.
The conversion registry here covers the stdlib types (str, int,
float, bool, list[str], pathlib.Path,
datetime.datetime, datetime.date) and any enum.Enum. QGIS-only
types (e.g. QColor) are registered by the modules that own them —
see settings, which also adds the QGIS-backed proxies
(QgsSettings, QgsProject, layer properties) on top of this base.
Dict-like and typed-descriptor access mirror how a typed entry sits over a flat store:
env = EnvironmentVariables()
env["MY_FLAG"] = True # stored as the string "True"
env.get("MY_PORT", 5678, cast=int) # -> int, with a default
class DebugEnv(EnvironmentVariables):
QGIS_DEBUGPY = BoolEnvVar(default=False)
QGIS_DEBUGPY_PORT = IntEnvVar(default=5678)
DebugEnv().QGIS_DEBUGPY # -> bool
Module Attributes
Union of representations every backend can persist natively. |
Functions
|
Rebuild a value of target_type from a stored representation. |
|
Register conversion callables for py_type, replacing any existing entry. |
|
Convert a Python value into a representation a QGIS backend can persist. |
Classes
|
A |
|
Descriptor mapping a class attribute to a typed environment variable. |
|
Dict-like proxy over the process environment ( |
|
A |
|
An |
Common |
|
|
A |
|
A |
|
Round-trips a single Python type to and from a backend-storable representation. |
- class stratified_packager.toolbelt.mapping_proxy.BoolEnvVar(*, default, description='', key=None)[source]
A
boolenvironment variable, parsed via the converter registry.
- class stratified_packager.toolbelt.mapping_proxy.EnvVar(cast, default, description='', *, key=None)[source]
Descriptor mapping a class attribute to a typed environment variable.
Declare instances as class attributes of an
EnvironmentVariablessubclass; the attribute name is used as the variable name unless key overrides it. Reads and writes route through the owningEnvironmentVariablesproxy (hence the converter registry), soschema.NAMEandschema["NAME"]address the same variable — the former typed and defaulted.Concrete subclasses (
BoolEnvVarand siblings) bindTby forwarding the target type to__init__.- __init__(cast, default, description='', *, key=None)[source]
Initialize the descriptor.
- Parameters:
cast (
type[TypeVar(T)]) – Target Python type the stored string is converted to on read.default (
TypeVar(T)) – Value returned when the variable is unset.description (
str) – Human-readable description (documentation only).key (
str|None) – Variable name; defaults to the attribute name the descriptor is assigned to.
- reset(instance)[source]
Unset the variable so its default applies again.
- Parameters:
instance (
EnvironmentVariables) – The owning proxy instance.- Return type:
- _default: T
- class stratified_packager.toolbelt.mapping_proxy.EnvironmentVariables(environ=None)[source]
Dict-like proxy over the process environment (
os.environ).Reads and writes environment variables through the shared converter registry, so callers get typed access without hand-rolling string parsing:
env = EnvironmentVariables() env.get("MY_PORT", 5678, cast=int) # -> int, with a default env["MY_FLAG"] = True # stored as the string "True"
Subclass it and declare
EnvVardescriptors for a typed, self-documenting schema —self.<NAME>returns the typed value (its default when unset) andself.<NAME> = valuewrites it, while the instance stays a full dict-like proxy for any other variable:class DebugEnv(EnvironmentVariables): QGIS_DEBUGPY = BoolEnvVar(default=False) QGIS_DEBUGPY_PORT = IntEnvVar(default=5678) env = DebugEnv() env.QGIS_DEBUGPY # -> bool env.QGIS_DEBUGPY_PORT # -> int
It touches no QGIS objects, so it is usable from any thread; writes do, however, mutate process-global state. The environment stores only strings, so scalar types (
bool,int,float,str,Path) round-trip, while structured values are stored as theirstrform and do not.- Parameters:
environ (
MutableMapping[str,str] |None)
- __init__(environ=None)[source]
Initialize the proxy.
- Parameters:
environ (
MutableMapping[str,str] |None) – Backing environment mapping; defaults toos.environ.
- _abc_impl = <_abc._abc_data object>
- _environ: MutableMapping[str, str]
- class stratified_packager.toolbelt.mapping_proxy.FloatEnvVar(*, default, description='', key=None)[source]
A
floatenvironment variable.
- class stratified_packager.toolbelt.mapping_proxy.IntEnvVar(*, default, description='', key=None)[source]
An
intenvironment variable.
- class stratified_packager.toolbelt.mapping_proxy.MappingProxy[source]
Common
MutableMappingplumbing for the proxies.Subclasses implement four hooks —
_raw_get(),_raw_set(),_raw_del(), and_raw_keys()— and inherit consistent[]/in/len/iteration semantics plus a typedget(). The typed-read routing lives in_typed_get(), which backends with type-specific read APIs may override.- abstractmethod _raw_del(key)[source]
Delete key from the backend (only called when the key is present).
- abstractmethod _raw_set(key, value)[source]
Write value at key (already converted via
to_storage()).
- _typed_get(key, cast)[source]
Read key and convert it to cast when present.
The default uses
_raw_get()plusfrom_storage(); backends with type-specific read APIs override this.
- get(key, default=None, *, cast=None)[source]
- Overloads:
self, key (str) → object | None
self, key (str), default (object) → object
self, key (str), default (T | None), cast (type[T]) → T | None
Return the value for key, optionally converted to cast.
- Parameters:
- Returns:
The (optionally converted) value, or default when absent.
- _abc_impl = <_abc._abc_data object>
- class stratified_packager.toolbelt.mapping_proxy.PathEnvVar(*, default, description='', key=None)[source]
A
Pathenvironment variable.
- class stratified_packager.toolbelt.mapping_proxy.StrEnvVar(*, default, description='', key=None)[source]
A
strenvironment variable.
- class stratified_packager.toolbelt.mapping_proxy.TypeConverter(serialize, deserialize)[source]
Round-trips a single Python type to and from a backend-storable representation.
Instances are registered with
register_converter()and looked up byto_storage()andfrom_storage().- Parameters:
- __init__(serialize, deserialize)[source]
Store the two conversion callables.
- Parameters:
serialize (
Callable[[TypeVar(T)],str|int|float|bool|list[str]]) – Callable turning aTinto aStorableValue.deserialize (
Callable[[object],TypeVar(T)]) – Callable rebuilding aTfrom a stored value (which may have been read back as a different type, e.g. aboolpersisted as the string"true").
- serialize: Final[Callable[[T], StorableValue]]
- stratified_packager.toolbelt.mapping_proxy._find_converter(klass)[source]
Return the converter registered for klass or its nearest registered base.
Walking the MRO lets a converter registered for an abstract base (e.g.
pathlib.Path) handle the concrete instances QGIS hands back (e.g.pathlib.PosixPath/pathlib.WindowsPath).- Parameters:
klass (
type) – The type to resolve a converter for.- Return type:
- Returns:
The matching
TypeConverter, orNoneif none is registered.
- stratified_packager.toolbelt.mapping_proxy._is_item_iterable(value)[source]
Return whether value should be treated as a sequence of stringifiable items.
True for any
Iterableexcept strings, bytes, and mappings: a string is stored whole (never exploded into characters), bytes are stored whole, and a mapping is not silently reduced to its keys.
- stratified_packager.toolbelt.mapping_proxy._to_str_list(raw)[source]
Coerce a stored value into a list of strings.
- stratified_packager.toolbelt.mapping_proxy.from_storage(raw, target_type)[source]
Rebuild a value of target_type from a stored representation.
enum.Enumsubclasses are reconstructed by value lookup (target_type(raw)); every other type must have a converter registered for it or a base, whosedeserializecallable is then applied.- Parameters:
- Return type:
TypeVar(T)- Returns:
raw converted to target_type.
- Raises:
TypeError – If no converter is registered for target_type.
ValueError – If the registered converter cannot parse raw (e.g. a non-numeric string).
- stratified_packager.toolbelt.mapping_proxy.register_converter(py_type, serialize, deserialize)[source]
Register conversion callables for py_type, replacing any existing entry.
- Parameters:
py_type (
type[TypeVar(T)]) – The Python type the converter handles.serialize (
Callable[[TypeVar(T)],str|int|float|bool|list[str]]) – Callable turning a py_type value into a storable value.deserialize (
Callable[[object],TypeVar(T)]) – Callable rebuilding a py_type value from a stored value.
- Return type:
- stratified_packager.toolbelt.mapping_proxy.to_storage(value)[source]
Convert a Python value into a representation a QGIS backend can persist.
enum.Enummembers are reduced to theirvalue; otherwise the converter registered for the value’s type (or nearest registered base) is used. Values whose type has no converter are returned unchanged (assumed natively storable).
- stratified_packager.toolbelt.mapping_proxy._CONVERTERS: Final[dict[type, TypeConverter[Any]]] = {<class 'bool'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'datetime.date'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'datetime.datetime'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'float'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'int'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'list'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'pathlib.Path'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, <class 'str'>: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>, qgis.PyQt.QtGui.QColor: <stratified_packager.toolbelt.mapping_proxy.TypeConverter object>}
Registry mapping each Python type to its
TypeConverter.