Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are re
| 39 | |
| 40 | @keras_export('keras.utils.CustomObjectScope') |
| 41 | class CustomObjectScope(object): |
| 42 | """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. |
| 43 | |
| 44 | Code within a `with` statement will be able to access custom objects |
| 45 | by name. Changes to global custom objects persist |
| 46 | within the enclosing `with` statement. At end of the `with` statement, |
| 47 | global custom objects are reverted to state |
| 48 | at beginning of the `with` statement. |
| 49 | |
| 50 | Example: |
| 51 | |
| 52 | Consider a custom object `MyObject` (e.g. a class): |
| 53 | |
| 54 | ```python |
| 55 | with CustomObjectScope({'MyObject':MyObject}): |
| 56 | layer = Dense(..., kernel_regularizer='MyObject') |
| 57 | # save, load, etc. will recognize custom object by name |
| 58 | ``` |
| 59 | """ |
| 60 | |
| 61 | def __init__(self, *args): |
| 62 | self.custom_objects = args |
| 63 | self.backup = None |
| 64 | |
| 65 | def __enter__(self): |
| 66 | self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() |
| 67 | for objects in self.custom_objects: |
| 68 | _GLOBAL_CUSTOM_OBJECTS.update(objects) |
| 69 | return self |
| 70 | |
| 71 | def __exit__(self, *args, **kwargs): |
| 72 | _GLOBAL_CUSTOM_OBJECTS.clear() |
| 73 | _GLOBAL_CUSTOM_OBJECTS.update(self.backup) |
| 74 | |
| 75 | |
| 76 | @keras_export('keras.utils.custom_object_scope') |
no outgoing calls