Cucumber Expressions for Python

19.0.0 · active · verified Fri Apr 10

Cucumber Expressions is an alternative to Regular Expressions with a more intuitive syntax, designed for defining step definitions in a human-readable format. This Python library provides the parsing and matching capabilities for these expressions. The current version is 19.0.0, and it maintains an active development status with regular updates, including recent Python-specific changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create basic Cucumber Expressions using built-in parameter types like `{int}` and how to define and register your own custom parameter types (`{color}` in this example) to extend the expression matching capabilities. It shows how to initialize `Expression` objects with a `ParameterTypeRegistry` and use the `match` method to extract values.

from cucumber_expressions.expression import Expression
from cucumber_expressions.parameter_type import ParameterType, ParameterTypeRegistry

# --- Basic Expression Matching ---
# Create a registry (required even for built-in types)
registry = ParameterTypeRegistry()

# Define an expression with a built-in parameter type
expression_int = Expression("I have {int} cucumbers in my belly", registry)
match_int = expression_int.match("I have 42 cucumbers in my belly")
print(f"Match for 'I have 42 cucumbers': {match_int.group_values if match_int else None}")

match_float = expression_int.match("I have 3.14 cucumbers in my belly")
print(f"Match for 'I have 3.14 cucumbers' (expects int): {match_float.group_values if match_float else None}")

# --- Custom Parameter Type ---
class Color:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return f"Color('{self.name}')"

# Define a custom parameter type and add to the registry
color_parameter_type = ParameterType(
    name="color",
    regexp="red|blue|yellow",
    type=Color,
    transformer=lambda s: Color(s)
)
registry.define_parameter_type(color_parameter_type)

# Use the custom parameter type in an expression
expression_color = Expression("I have a {color} ball", registry)
match_color = expression_color.match("I have a red ball")
print(f"Match for 'I have a red ball': {match_color.group_values if match_color else None}")

match_color_fail = expression_color.match("I have a green ball")
print(f"Match for 'I have a green ball': {match_color_fail.group_values if match_color_fail else None}")

view raw JSON →