with_lapdf

bapsflib.utils.decorators.with_lapdf(wfunc=None, *, filename: str | None = None)

Context decorator for managing the opening and closing LaPD HDF5 Files (bapsflib.lapd._hdf.file.File). An instance of the LaPD HDF5 file is injected into the decorated function at the end of the positional arguments. The decorator is primarily designed for use on test methods, but can also be used as a function decorator.

Parameters:
  • wfunc – function or method to be wrapped

  • filename – name of the BaPSF HDF5 file

Example:

The HDF5 filename can be passed to the decorator in three ways (listed by predominance):

  1. The wrapped function arguments.

  2. If the wrapped function is a method, then through the appropriately named self attributes.

  3. The decorator keywords.

Defined with wrapped function arguments:

>>> # as function keywords
>>> @with_lapdf
... def foo(lapdf, **kwargs):
...     # * bf will be the HDF5 file object
...     # * do whatever is needed with bf and @with_bf will close
...     #   the file at the end
...     return lapdf.filename
>>> foo(filename='test.hdf5')
'test.hdf5'
>>>
>>> # as a function argument
>>> @with_lapdf
... def foo(filename, lapdf, **kwargs):
...     # use bf
...     return lapdf.filename
... foo('test.hdf5')
'test.hdf5'

Defined with wrapped method attributes:

>>> # use `self` to pass file settings
>>> class BehaveOnFile:
...     def __init__(self):
...         super().__init__()
...         self.filename = 'test.hdf5'
...
...     @with_bf
...     def foo(self, lapdf, **kwargs):
...         return lapdf.filename
>>> a = BehaveOnFile()
>>> a.foo()
'test.hdf5'
>>>
>>> # but keywords will still take precedence
>>> a.foo(filename='test_2.hdf5')
'test_2.hdf5'

Defined with decorator keywords:

>>> # as function keywords
>>> @with_bf(filename='test.hdf5')
... def foo(lapdf, **kwargs):
...     return lapdf.filename
>>> foo()
'test.hdf5'
>>>
>>> # function keywords will still take precedence
>>> foo(filename='test_2.hdf5')
'test_2.hdf5'