Path: blob/master/src/sage/libs/gap/context_managers.py
8815 views
"""1Context Managers for LibGAP23This module implements a context manager for global variables. This is4useful since the behavior of GAP is sometimes controlled by global5variables, which you might want to switch to a different value for a6computation. Here is an example how you are suppose to use it from7your code. First, let us set a dummy global variable for our example::89sage: libgap.set_global('FooBar', 123)1011Then, if you want to switch the value momentarily you can write::1213sage: with libgap.global_context('FooBar', 'test'):14....: print libgap.get_global('FooBar')15"test"1617Afterward, the global variable reverts to the previous value::1819sage: print libgap.get_global('FooBar')201232122The value is reset even if exceptions occur::2324sage: with libgap.global_context('FooBar', 'test'):25....: print libgap.get_global('FooBar')26....: raise ValueError(libgap.get_global('FooBar'))27Traceback (most recent call last):28...29ValueError: "test"30sage: print libgap.get_global('FooBar')3112332"""333435###############################################################################36# Copyright (C) 2012, Volker Braun <[email protected]>37#38# Distributed under the terms of the GNU General Public License (GPL)39# as published by the Free Software Foundation; either version 2 of40# the License, or (at your option) any later version.41# http://www.gnu.org/licenses/42###############################################################################4344from sage.libs.gap.libgap import libgap454647class GlobalVariableContext():4849def __init__(self, variable, value):50"""51Context manager for GAP global variables.5253It is recommended that you use the54:meth:`sage.libs.gap.libgap.Gap.global_context` method and not55construct objects of this class manually.5657INPUT:5859- ``variable`` -- string. The variable name.6061- ``value`` -- anything that defines a GAP object.6263EXAMPLES::6465sage: libgap.set_global('FooBar', 1)66sage: with libgap.global_context('FooBar', 2):67....: print libgap.get_global('FooBar')68269sage: libgap.get_global('FooBar')70171"""72self._variable = variable73self._new_value = value7475def __enter__(self):76"""77Called when entering the with-block7879EXAMPLES::8081sage: libgap.set_global('FooBar', 1)82sage: with libgap.global_context('FooBar', 2):83....: print libgap.get_global('FooBar')84285sage: libgap.get_global('FooBar')86187"""88self._old_value = libgap.get_global(self._variable)89libgap.set_global(self._variable, self._new_value)9091def __exit__(self, exc_type, exc_val, exc_tb):92"""93Called when exiting the with-block9495EXAMPLES::9697sage: libgap.set_global('FooBar', 1)98sage: with libgap.global_context('FooBar', 2):99....: print libgap.get_global('FooBar')1002101sage: libgap.get_global('FooBar')1021103"""104libgap.set_global(self._variable, self._old_value)105return False106107108