Managing pure-python and C-ext code

Module openquake.hazardlib.speedups contains internal utilities for managing alternative implementation of the same functionality depending on their availability.

class openquake.hazardlib.speedups.SpeedupsRegistry[source]

Speedups registry allows to manage alternative implementations of functions. Typical use case for it is something like this:

# in the module namespace

def do_foo(foo, bar):
    # code in pure python
    ...

def do_bar(baz, quux):
    # code in pure python
    ...

# in the end of the module

try:
    import _foobar_speedups
except ImportError:
    import warnings
    warnings.warn("foobar speedups are not available", RuntimeWarning)
else:
    from openquake.hazardlib import speedups

    def _c_do_foo(foo, bar):
        return _foobar_speedups.do_foo(foo, bar)
    speedups.register(do_foo, _c_do_foo)
    del _c_do_foo

    def _c_do_bar(baz, quux):
        return _foobar_speedups.do_foo(baz, quux)
    speedups.register(do_bar, _c_do_bar)
    del _c_do_bar

Global registry is being used here. All speedups are enabled by default. In order to disable them, use disable().

disable()[source]

Set implementation to “original” for all the registered functions.

enable()[source]

Set implementation to “alternative” for all the registered functions.

register(func, altfunc)[source]

Add a function and its alternative implementation to the registry.

If registry is enabled, function code will be substituted by an alternative implementation immediately.

Parameters:
  • func – A function object to patch.
  • altfunc – An alternative implementation of the function. Must have the same signature and is supposed to behave exactly the same way as func.
openquake.hazardlib.speedups.disable = <bound method SpeedupsRegistry.disable of <openquake.hazardlib.speedups.SpeedupsRegistry object at 0x7f6bdda31cd0>>

Global (default) registry disable().

openquake.hazardlib.speedups.enable = <bound method SpeedupsRegistry.enable of <openquake.hazardlib.speedups.SpeedupsRegistry object at 0x7f6bdda31cd0>>

Global (default) registry enable().

openquake.hazardlib.speedups.register = <bound method SpeedupsRegistry.register of <openquake.hazardlib.speedups.SpeedupsRegistry object at 0x7f6bdda31cd0>>

Global (default) registry register().