operations.conditional

Module for conditional operations to control flow in the pipeline.

Classes

  • IfElse - Executes different operations based on the condition.

  • Break - Stops the pipeline execution.

  • Continue - Skips the operation and continues with the next one.

class IfElse(condition: Callable[[Any], bool], if_: BaseOperation, else_: BaseOperation)[source]

Bases: OperationSearcherMixin

Operation to control flow in the pipeline. Allows to execute different operations based on the condition.

Example

>>> from soupsavvy.operations import IfElse, Operation
... operation = IfElse(
...     lambda x: x == 0,
...     Operation(lambda x: None),
...     Operation(lambda x: x / 100),
... )
... operation.execute(0)
None
... operation.execute(100)
1

Implements TagSearcher interface for convenience. It can conditionally apply operations to the element and can be used as model field.

Example

>>> from soupsavvy.operations import IfElse, Operation, Text
... operation = IfElse(
...     lambda x: x.get("id") == "user",
...     Text(),
...     Href(),
... )
... operation.find(user_element)
username
... operation.find(other_element)
www.example.com
__init__(condition: Callable[[Any], bool], if_: BaseOperation, else_: BaseOperation) None[source]

Initializes `IfEls`e operation with condition and two operations.

Parameters

conditionCallable[[Any], bool]

Condition to check if the operation should be executed. If callable returns True, if_ operation is executed, otherwise else_.

if_BaseOperation

Operation to execute if condition is fulfilled.

else_BaseOperation

Operation to execute if condition is not fulfilled.

class Break[source]

Bases: OperationSearcherMixin

Operation to break the pipeline execution and return the current result. Can be used in selection/operation pipelines with IfElse operation to conditionally stop the execution.

Example

>>> from soupsavvy.operations import Break, IfElse, Operation
... operation = IfElse(
...     lambda x: x == 0,
...     Break(),
...     Operation(lambda x: 100 / x),
... ) | Operation(lambda x: x + 1)
... operation.execute(0)
0
... operation.execute(100)
2

If Break operation is executed, the pipeline will stop and return the result, so next operation is not executed.

class Continue[source]

Bases: OperationSearcherMixin

Operation to skip the current operation ad move to the next one. Can be used in selection/operation pipelines with IfElse operation to conditionally skip the operation.

Example

>>> from soupsavvy.operations import Continue, IfElse, Operation
... operation = IfElse(
...     lambda x: x == 0,
...     Continue(),
...     Operation(lambda x: x / 100),
... ) | Operation(lambda x: x - 1)
... operation.execute(0)
-1
... operation.execute(100)
0

If Continue operation is executed, operation is skipped and the next one is executed.