Utilities¶
chanfig.utils
¶
NULL
¶
NULL class.
get method in CHANfiG may accept None or Ellipse(...) as value of default.
Therefore, it is mandatory to have a different default value for default.
Null is an instance of NULL and is recommended to be used as obj is Null.
Source code in chanfig/utils/null.py
SafeEvalError
¶
conform_annotation
¶
Check if data is valid according to the expected type.
This function handles complex type annotations including: - Basic types (int, str, etc.) - Container types (List, Dict, etc.) - Union types (including Optional) - Nested generic types
Source code in chanfig/utils/annotation.py
get_annotations
¶
get_annotations(
obj,
*,
globalns: Mapping | None = None,
localns: Mapping | None = None,
eval_str: bool = True
) -> Mapping
Compute the annotations dict for an object.
obj may be a callable, class, or module. Passing in an object of any other type raises TypeError.
Returns a dict. get_annotations() returns a new dict every time it’s called; calling it twice on the same object will return two different but equivalent dicts.
This function handles several details for you:
- If
eval_stris true, values of type str will be un-stringized usingeval(). This is intended for use with stringized annotations (from __future__ import annotations). globalnsfall back to public member oftyping.- If obj doesn’t have an annotations dict, returns an empty dict. (Functions and methods always have an annotations dict; classes, modules, and other types of callables may not.)
- Ignores inherited annotations on classes. If a class doesn’t have its own annotations dict, returns an empty dict.
- All accesses to object members and dict values are done
using
getattr()anddict.get()for safety. - Always, always, always returns a freshly-created dict.
eval_str controls whether or not values of type str are replaced
with the result of calling eval() on those values:
- If
eval_stris true, eval() is called on values of type str. - If
eval_stris false (the default), values of type str are unchanged.
globalns and localns are passed in to eval(); see the documentation
for eval() for more information.
globalns fall back to public member of typing.
If either globalns or localns is
None, this function may replace that value with a context-specific
default, contingent on type(obj):
- If
objis a module, globalns defaults toobj.__dict__. - If
objis a class, globalns defaults tosys.modules[obj.__module__].__dict__andlocalnsdefaults to the obj class namespace. - If
objis a callable,globalnsdefaults toobj.__globals__, although if obj is a wrapped function (using functools.update_wrapper()) it is first unwrapped. - If
objis an instance,globalnsdefaults tosys.modules[obj.__module__].__dict__and localns defaults to the obj class namespace.
Source code in chanfig/utils/annotation.py
| Python | |
|---|---|
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
get_cached_annotations
¶
Lightweight cached wrapper around get_annotations keyed by class.
By default, the returned mapping is copied to preserve the original
get_annotations contract of producing a fresh dict for each call.
Internal callers may set copy=False to retrieve a read-only cached mapping
and avoid per-call dict allocations in hot paths.
Source code in chanfig/utils/annotation.py
honor_annotation
¶
Attempt to convert data to match the expected type annotation.
This function tries to honor the type annotation by converting the data when possible, rather than rejecting it. It works with: - Basic types (int, str, etc.) - Container types (List, Dict, etc.) - Union types (including Optional) - Nested generic types
Unlike conform_annotation which validates type compatibility,
this function tries to adapt the data to match the annotation.
Examples:
| Python Console Session | |
|---|---|
Source code in chanfig/utils/annotation.py
| Python | |
|---|---|
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
apply
¶
Apply func to all children of obj.
Note that this method is meant for non-in-place modification of obj and should return the original object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Object to apply function. |
required |
|
Callable
|
Function to be applied. |
required |
|
Any
|
Positional arguments to be passed to |
()
|
|
Any
|
Keyword arguments to be passed to |
{}
|
See Also
[apply_][chanfig.utils.apply.apply_]: Apply an in-place operation.
Source code in chanfig/utils/functional.py
apply_
¶
Apply func to all children of obj.
Note that this method is meant for in-place modification of obj and should return the modified object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Object to apply function. |
required |
|
Callable
|
Function to be applied. |
required |
|
Any
|
Positional arguments to be passed to |
()
|
|
Any
|
Keyword arguments to be passed to |
{}
|
See Also
[apply][chanfig.utils.apply.apply]: Apply a non-in-place operation.
Source code in chanfig/utils/functional.py
parse_bool
¶
Convert various types of values to boolean.
This function converts different input types (bool, str, int) to their boolean equivalent.
Examples:
| Python Console Session | |
|---|---|
Source code in chanfig/utils/functional.py
suggest_key
¶
Suggest the closest key from candidates to name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
The queried name. |
required |
|
Iterable[Any]
|
An iterable of candidate names. |
required |
|
float
|
Similarity threshold passed to :func: |
0.75
|
Source code in chanfig/utils/functional.py
to_chanfig
¶
Convert arbitrary data structure to CHANfiG objects when possible.
This function recursively converts mappings to FlatDict instances and handles nested structures of arbitrary depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Object to be converted. |
required |
|
type | None
|
Class to use for creating FlatDict instances. Defaults to |
None
|
Examples:
| Python Console Session | |
|---|---|
Source code in chanfig/utils/functional.py
to_dict
¶
Convert an object to a dict.
Note that when converting a set object, it may be converted to a tuple object if its values is not hashable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
Object to be converted. |
required |
|
bool
|
Whether to flatten nested structures. |
False
|
Examples:
| Python Console Session | |
|---|---|
Source code in chanfig/utils/functional.py
find_circular_reference
¶
Find circular references in a dependency graph.
This function performs a depth-first search to detect any circular references in a graph represented as a mapping of nodes to their dependencies.
Source code in chanfig/utils/placeholder.py
find_placeholders
¶
Find all placeholders in text, including nested ones.
This function searches for placeholders in the format ${name} and returns a list of all placeholder names found, including those that are nested within other placeholders.
Examples:
| Python Console Session | |
|---|---|
Source code in chanfig/utils/placeholder.py
safe_eval_expr
¶
Safely evaluate a limited arithmetic expression against a context of names.
Supported
- Literals (ints, floats, strings)
- Names (looked up in
context) - Unary ± on numbers
- Binary ops: +, -, *, /, //, %, **
- Parentheses (handled by the AST parser)
Anything else raises SafeEvalError.