Set an item with check for allownew. Examples -------- >>> s = Struct() >>> s['a'] = 10 >>> s.allow_new_attr(False) >>> s['a'] = 10 >>> s['a'] 10 >>> try: ... s['b'] = 20 ... except KeyError: ...
(self, key, value)
| 64 | dict.__init__(self, *args, **kw) |
| 65 | |
| 66 | def __setitem__(self, key, value): |
| 67 | """Set an item with check for allownew. |
| 68 | |
| 69 | Examples |
| 70 | -------- |
| 71 | |
| 72 | >>> s = Struct() |
| 73 | >>> s['a'] = 10 |
| 74 | >>> s.allow_new_attr(False) |
| 75 | >>> s['a'] = 10 |
| 76 | >>> s['a'] |
| 77 | 10 |
| 78 | >>> try: |
| 79 | ... s['b'] = 20 |
| 80 | ... except KeyError: |
| 81 | ... print('this is not allowed') |
| 82 | ... |
| 83 | this is not allowed |
| 84 | """ |
| 85 | if not self._allownew and key not in self: |
| 86 | raise KeyError( |
| 87 | "can't create new attribute %s when allow_new_attr(False)" % key) |
| 88 | dict.__setitem__(self, key, value) |
| 89 | |
| 90 | def __setattr__(self, key, value): |
| 91 | """Set an attr with protection of class members. |