Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, `bunch["value_key"]`, or by an attribute, `bunch.value_key`. Examples -------- >>> from
| 5 | |
| 6 | |
| 7 | class Bunch(dict): |
| 8 | """Container object exposing keys as attributes. |
| 9 | |
| 10 | Bunch objects are sometimes used as an output for functions and methods. |
| 11 | They extend dictionaries by enabling values to be accessed by key, |
| 12 | `bunch["value_key"]`, or by an attribute, `bunch.value_key`. |
| 13 | |
| 14 | Examples |
| 15 | -------- |
| 16 | >>> from sklearn.utils import Bunch |
| 17 | >>> b = Bunch(a=1, b=2) |
| 18 | >>> b['b'] |
| 19 | 2 |
| 20 | >>> b.b |
| 21 | 2 |
| 22 | >>> b.a = 3 |
| 23 | >>> b['a'] |
| 24 | 3 |
| 25 | >>> b.c = 6 |
| 26 | >>> b['c'] |
| 27 | 6 |
| 28 | """ |
| 29 | |
| 30 | def __init__(self, **kwargs): |
| 31 | super().__init__(kwargs) |
| 32 | |
| 33 | # Map from deprecated key to warning message |
| 34 | self.__dict__["_deprecated_key_to_warnings"] = {} |
| 35 | |
| 36 | def __getitem__(self, key): |
| 37 | if key in self.__dict__.get("_deprecated_key_to_warnings", {}): |
| 38 | warnings.warn( |
| 39 | self._deprecated_key_to_warnings[key], |
| 40 | FutureWarning, |
| 41 | ) |
| 42 | return super().__getitem__(key) |
| 43 | |
| 44 | def _set_deprecated(self, value, *, new_key, deprecated_key, warning_message): |
| 45 | """Set key in dictionary to be deprecated with its warning message.""" |
| 46 | self.__dict__["_deprecated_key_to_warnings"][deprecated_key] = warning_message |
| 47 | self[new_key] = self[deprecated_key] = value |
| 48 | |
| 49 | def __setattr__(self, key, value): |
| 50 | self[key] = value |
| 51 | |
| 52 | def __dir__(self): |
| 53 | return self.keys() |
| 54 | |
| 55 | def __getattr__(self, key): |
| 56 | try: |
| 57 | return self[key] |
| 58 | except KeyError: |
| 59 | raise AttributeError(key) |
| 60 | |
| 61 | def __setstate__(self, state): |
| 62 | # Bunch pickles generated with scikit-learn 0.16.* have a non |
| 63 | # empty __dict__. This causes a surprising behaviour when |
| 64 | # loading these pickles scikit-learn 0.17: reading bunch.key |
no outgoing calls
searching dependent graphs…