pop#
- class brainstate.environ.pop(key, default=<object object>, *, env=None)[source]#
Remove and return a value from the global environment.
This function removes a key from the global environment settings and returns its value. If the key is not found, it returns the default value if provided, or raises KeyError.
Note that this function only affects global settings, not context values. Keys in active contexts are not affected.
- Parameters:
key (
str) – The environment key to remove.default (
Any) – Default value to return if key is not found. If not provided, raises KeyError for missing keys.env (
EnvironmentState|None) – The environment state to modify. If None, uses the global environment.
- Returns:
The value that was removed from the environment.
- Return type:
- Raises:
KeyError – If key is not found and no default is provided.
ValueError – If attempting to pop a key that is currently in a context.
Examples
Basic usage:
>>> import brainstate.environ as env >>> >>> # Set a value >>> env.set(temp_param='temporary') >>> print(env.get('temp_param')) # 'temporary' >>> >>> # Pop the value >>> value = env.pop('temp_param') >>> print(value) # 'temporary' >>> >>> # Value is now gone >>> env.get('temp_param', default=None) # None
With default value:
>>> import brainstate.environ as env >>> >>> # Pop non-existent key with default >>> value = env.pop('nonexistent', default='default_value') >>> print(value) # 'default_value'
Pop multiple values:
>>> import brainstate.environ as env >>> >>> # Set multiple values >>> env.set(param1='value1', param2='value2', param3='value3') >>> >>> # Pop them one by one >>> v1 = env.pop('param1') >>> v2 = env.pop('param2') >>> >>> # param3 still exists >>> print(env.get('param3')) # 'value3'
Context protection:
>>> import brainstate.environ as env >>> >>> env.set(protected='global_value') >>> >>> with env.context(protected='context_value'): ... # Cannot pop a key that's in active context ... try: ... env.pop('protected') ... except ValueError as e: ... print("Cannot pop key in active context")
Using custom environment:
>>> import brainstate.environ as env >>> >>> custom_env = env.EnvironmentState() >>> env.set(param='value', env=custom_env) >>> value = env.pop('param', env=custom_env) >>> print(value) # 'value'
Notes
This function only removes keys from global settings
Keys that are currently overridden in active contexts cannot be popped
Special keys like ‘platform’ and ‘host_device_count’ can be popped but their system-level values remain accessible through get_platform() etc.
Registered callbacks are NOT triggered when popping values