python-autoviv: Autovivification for Python Dictionaries
python-autoviv provides autovivification for Python dictionaries, allowing the creation of deeply nested data structures on-the-fly simply by accessing keys. It mimics Perl's default behavior, eliminating the need for explicit intermediate dictionary initializations. The current version is 1.0.4, with releases focusing on stability and minor enhancements.
Common errors
-
ModuleNotFoundError: No module named 'python_autoviv'
cause The PyPI package is `python-autoviv`, but the actual Python module name to import from is `autoviv`.fixChange your import statement from `from python_autoviv import AutoVivification` to `from autoviv import AutoVivification`. -
Dictionary key created unexpectedly without explicit assignment or `KeyError`
cause This is the core behavior of autovivification. Any access to a non-existent key path (e.g., `d['new_key']`) implicitly creates a new `AutoVivification` object at that key, rather than raising a `KeyError`.fixUnderstand that `AutoVivification` is designed to create keys on access. If you need standard `KeyError` behavior or want to explicitly check for key existence, use `if 'key' in my_autoviv_dict:` or `my_autoviv_dict.get('key', default_value)`.
Warnings
- gotcha Autovivification can mask typos. If you misspell a key (e.g., `d['usrname']` instead of `d['username']`), it will silently create a new key instead of raising a `KeyError`, potentially leading to hard-to-debug data inconsistencies.
- gotcha Every intermediate key access implicitly creates a new `AutoVivification` instance if the path doesn't exist. For very sparse or deeply nested data structures, this could consume more memory than a carefully constructed regular dictionary, as many empty intermediate objects might be instantiated.
- gotcha Converting an `AutoVivification` instance to a standard Python `dict` using `dict(autoviv_instance)` will only convert the top level. Nested `AutoVivification` objects within the structure will remain `AutoVivification` instances, not standard `dict`s.
Install
-
pip install python-autoviv
Imports
- AutoVivification
from python_autoviv import AutoVivification
from autoviv import AutoVivification
Quickstart
from autoviv import AutoVivification
d = AutoVivification()
d[1]['one'][2]['two'] = "Nested is as nested does."
d[1]['one'][2]['three'] = "Or so they say."
print(d)
# Expected output: {1: {'one': {2: {'two': 'Nested is as nested does.', 'three': 'Or so they say.'}}}}
# Accessing a non-existent path creates it
if 'new_key' not in d[1]['one']:
print("'new_key' does not exist in d[1]['one'] initially.")
d[1]['one']['new_key']['sub_key'] = 42
print(f"Value at d[1]['one']['new_key']['sub_key']: {d[1]['one']['new_key']['sub_key']}")
# Expected output: Value at d[1]['one']['new_key']['sub_key']: 42