with_open#

gwpy.io.utils.with_open(func: Callable[P, T], mode: str = 'r', pos: int = 0) Callable[P, T][source]#
gwpy.io.utils.with_open(
func: None = None,
mode: str = 'r',
pos: int = 0,
) Callable[[Callable[P, T]], Callable[P, T]]

Decorate a function to ensure the chosen argument is an open file.

Parameters:
funccallable

the function to decorate

modestr, optional

the mode with which to open files

posint, optional

which argument to look at

Examples

To ensure that the first argument is an open read-only file, just use the decorator without functional parentheses or arguments:

>>> @with_open
>>> def my_func(pathorfile, *args, **kwargs)
>>>     ...

To ensure that the second argument (position 1) is a file open for writing:

>>> @with_open(mode="w", pos=1)
>>> def my_func(stuff, pathorfile, *args, **kwargs)
>>>     stuff.write_to(pathorfile, *args, **kwargs)