5.2. spy.decorators
¶
This module contains various function decorators for use in spy fragments.
-
@
spy.decorators.
accumulate
[source]¶ -
--accumulate
,
-a
¶
Accumulate values into an iterator by calling
spy.collect()
, and pass that to the fragment.This can be used to write a fragment which executes at most once while passing data through:
-ma 'x = y;'
-
-
@
spy.decorators.
filter
[source]¶ -
--filter
,
-f
¶
Use the decorated fragment as a predicate—only elements for which the fragment returns a true value will be passed through.
-
-
@
spy.decorators.
keywords
[source]¶ -
--keywords
,
-k
¶
On fragments generated by the CLI, sets the local scope to the input value before each invocation. Normal Python functions cannot do this—trying to decorate them will raise :exception:`ValueError`.
-
-
@
spy.decorators.
many
[source]¶ -
--many
,
-m
¶
Call
spy.many()
with the result of the fragment.-
5.2.1. Literal decorators¶
On the CLI, these decorators take a literal string rather than Python code.
In Python-land, they expect to decorate a function that
returns (scope, string)
. They’re especially pointless for non-CLI uses,
and this documentation is written with CLI usage in mind.
-
@
spy.decorators.
interpolate
¶ -
--interpolate
,
-i
¶
Interpolate the literal argument as a
str.format()
format string.Keyword substitutions (
{foo}
) look up variable names. Positional substitutions ({2}
) are indexes into the value being processed.-
-
@
spy.decorators.
regex
[source]¶ -
--regex
,
--regexp
,
-R
¶
Match a regexp against the input using
re.match()
.-
5.2.2. Defining decorators¶
For integration with spy’s CLI and exception handling, decorators should be
created using decorator()
.
-
@
spy.decorators.
decorator
(name, *aliases[, doc=None][, prep=None][, takes_string=False])[source]¶ Turns a wrapper function into a spy decorator.
name
andaliases
are the CLI options that should refer to this decorator;doc
is the help output to be printed next to it by--help
.If
prep
is passed, it must be a callable taking one argument, the callable we are about to decorate, and the wrapper will be called as:wrapper(fn, v, context, opaque)
where opaque is whatever
prep
returns. Otherwise, the wrapper will be called with the first three arguments only.If
takes_string
is True, the command-line option will consume a literal string instead of Python code, andfn
will return a tuple of its local scope and the literal string value.For usage examples, see Adding decorators.