A Box whose attributes can only update existing fields. Use item assignment or dictionary methods to add fields explicitly. Values remain mutable, and nested dictionaries use StrictBox by default. .. code-block:: python settings = StrictBox(host="localhost", port=8000)
| 67 | |
| 68 | |
| 69 | class StrictBox(Box): |
| 70 | """ |
| 71 | A Box whose attributes can only update existing fields. |
| 72 | |
| 73 | Use item assignment or dictionary methods to add fields explicitly. Values |
| 74 | remain mutable, and nested dictionaries use StrictBox by default. |
| 75 | |
| 76 | .. code-block:: python |
| 77 | |
| 78 | settings = StrictBox(host="localhost", port=8000) |
| 79 | settings.port = 8080 |
| 80 | settings.prot = 8080 # raises BoxKeyError instead of adding a typo |
| 81 | settings["debug"] = False |
| 82 | settings.debug = True |
| 83 | |
| 84 | This restricts attribute assignment, not the shape or types of the data. |
| 85 | Replacing a nested dictionary establishes its new fields. Normal Box |
| 86 | options, property setters and declared internal attributes still apply. |
| 87 | """ |
| 88 | |
| 89 | def __setattr__(self, key, value): |
| 90 | if key == "_box_config" or key in self._box_internal_attrs: |
| 91 | return super().__setattr__(key, value) |
| 92 | |
| 93 | config = self._box_config |
| 94 | if config["__created"] and not config["frozen_box"] and key not in self._protected_keys: |
| 95 | resolved = config["__safe_keys"].get(self._safe_attr(key), key) |
| 96 | if _get_property_func(self, resolved)[1] is None: |
| 97 | if not _existing_destination(self, resolved): |
| 98 | raise BoxKeyError( |
| 99 | f'Cannot create field "{key}" through attribute assignment; use item assignment instead' |
| 100 | ) |
| 101 | |
| 102 | return super().__setattr__(key, value) |
no outgoing calls