Context Managers for LibGAP - C/C++ Library Interfaces

Skip to content
Back to top
View this page
Edit this page

# Context Managers for LibGAP

This module implements a context manager for global variables. This is useful since the behavior of GAP is sometimes controlled by global variables, which you might want to switch to a different value for a computation. Here is an example how you are suppose to use it from your code. First, let us set a dummy global variable for our example:

Sage

    sage: libgap.set_global('FooBar', 123)

Python

    >>> from sage.all import *
    >>> libgap.set_global('FooBar', Integer(123))

Then, if you want to switch the value momentarily you can write:

Sage

    sage: with libgap.global_context('FooBar', 'test'):
    ....:     print(libgap.get_global('FooBar'))
    test

[Python]

    >>> from sage.all import *
    >>> with libgap.global_context('FooBar', 'test'):
    ...     print(libgap.get_global('FooBar'))
    test

Afterward, the global variable reverts to the previous value:

Sage

    sage: print(libgap.get_global('FooBar'))
    123

Python

    >>> from sage.all import *
    >>> print(libgap.get_global('FooBar'))
    123

The value is reset even if exceptions occur:

Sage

    sage: with libgap.global_context('FooBar', 'test'):
    ....:     print(libgap.get_global('FooBar'))
    ....:     raise ValueError(libgap.get_global('FooBar'))
    Traceback (most recent call last):
    ...
    ValueError: test
    sage: print(libgap.get_global('FooBar'))
    123

[Python]

    >>> from sage.all import *
    >>> with libgap.global_context('FooBar', 'test'):
    ...     print(libgap.get_global('FooBar'))
    ...     raise ValueError(libgap.get_global('FooBar'))
    Traceback (most recent call last):
    ...
    ValueError: test
    >>> print(libgap.get_global('FooBar'))
    123

class sage.libs.gap.context_managers.GlobalVariableContext(variable, value)

  Bases: `object`

  Context manager for GAP global variables.

  It is recommended that you use the `sage.libs.gap.libgap.Gap.global_context()` method and not construct objects of this class manually.

  INPUT:

  - `variable` – string; the variable name

  - `value` – anything that defines a GAP object

  EXAMPLES:

  Sage

      sage: libgap.set_global('FooBar', 1)
      sage: with libgap.global_context('FooBar', 2):
      ....:     print(libgap.get_global('FooBar'))
      2
      sage: libgap.get_global('FooBar')
      1

  Python

      >>> from sage.all import *
      >>> libgap.set_global('FooBar', Integer(1))
      >>> with libgap.global_context('FooBar', Integer(2)):
      ...     print(libgap.get_global('FooBar'))
      2
      >>> libgap.get_global('FooBar')
      1