Skip to content

Language propsal: Keyword chaining #5849

Open

Description

@Lakitna

Split from #5846

Context

I was talking to a colleague that does not use Robot recently. Their OOP brain asked about a pattern that someone used in their tests, and if they could use a builder pattern instead. The builder pattern would work great in that particular situation, but Robot does not support it.

The situation that we talked about was related to building complex data objects. In this case, we needed ~10 highly specialized keywords after each other to build up a single data object. With that object, we can then test stuff. These highly specialized keywords use keywords of their own. It's a lot of code that is hard to understand in the best case scenario. But Robot forced us to make it harder to read than necessary in our opinion. I can't share the code itself because it's company code. Our discussion was about good ways of approaching this test requirement.

After this discussion, we briefly talked about what something like this could look like in Robot Framework. This issue is the outcome of that discussion.

Keyword chaining

Inspired by Object Oriented Programming and the builder pattern.

This approach is similar to the following python pattern:

foo().bar().baz()

I'm using -> based on a whim. This can, of course, use a different syntax.

In your test

What this could look like when you're writing a test.

GUI tests

Allows you to dedupe locators in a very readable (in my opinion) way.

Get Element    //button
->  Should have text    Hello world
->  Should have attribute    aria-enabled    true
->  Click

API tests

Allows you to define stuff in the 'correct' order. It's one of the main reasons I don't advise people to use Robot for pure API testing.

${request} =    POST    https://example.com
->  Add Header    Authorization    Bearer 923u49ujjidashuihdc8923yh98rhjd2
->  Add Header    Foo    Bar
->  Add Body    lorum=ipsum    dolor=sit

${response} =    ${request}    ->    Send

# Do something with the response

This gives us the reading order: Method -> URL -> Headers -> Body. Which feels much more natural to me compared to the current best Headers -> Body -> Method -> URL. The order still breaks a bit for complex bodies, where you'll have to create Body -> Method -> URL -> Headers.

In your resource file

How you can create these keywords in a resource file.

This approach does not work well in a resource file. It may have to be library-only. My best suggestion here is not great. It's essentially to give people a sanctioned way of using private keywords outside their defined file.

I would leave this part out entirely. Building chainables is an advanced thing, so forcing that to Python sounds like a fair tradeoff to me. Using chainables should be easy enough to use in .robot and .resource though.

Click to open partial code example
*** Keywords ***
Get Element
    [Arguments]    ${selector}
    VAR  @{chainable_keywords}    Should Have Text    Should Have Attribute    Click

    ${chainable_element} =    Create Chainable Object    context=${selector}    keywords=${chainable_keywords}
    RETURN   ${chainable_element}

Should Have Text
    [Tags]    robot:private
    [Arguments]    ${chainable_element}    ${text}
    # Truncated
    RETURN   ${chainable_element}


Should Have Attribute
    [Tags]    robot:private
    [Arguments]    ${chainable_element}    ${attribute}    ${value}
    # Truncated
    RETURN   ${chainable_element}


Click
    [Tags]    robot:private
    [Arguments]    ${chainable_element}
    # Truncated
    RETURN   ${chainable_element}

In your library

How you can create these keywords in a library.

This approach uses multiple classes due to the OOP influence. Let's use the GUI one above as an example. For the purposes of this example, I'll assume that Browser library fully supports this. I've used the explicit @libary and @keyword decorators for clarity.

Click to open partial code example
class Element:
  def __init__(self, element):
    self.el = element

  @keyword
  def should_have_text(self, expected_text):
    actual_text = somehow_get_element_text(self.el)
    should_be_equal(actual_text, expected_text)
    return self

  @keyword
  def should_have_attribute(self, attribute, expected_value):
    # truncated
    return self

  @keyword
  def click(self):
    # truncated
    return self

@library
class Browser:
  @keyword
  def get_element(self, locator):
    located_element = somehow_find_element_on_page(locator)
    return Element(located_element)

Couple of things of note:

  • The get_element keyword returns an Element object instance.
  • There is state in the Element instance. In this example, it's just self.el, but more can be added. This can be really useful. More useful sometimes than state in a library.
  • There are keywords on the Element class. This is the new part. These keywords can only be used from an Element instance. This is what the -> operator on the Robot side does on a technical level. It calls a keyword on a given object instance. These keywords don't exist in the global keyword store. This prevents name collisions, which keeps the keyword names short.
  • The keyword on the Element class all return self. This allows you to chain multiple of these keywords. It also allows you to return another class instance. For example, Request.send can return Response.

Please disagree with me

What do you think of this proposal? This would be a major language change and would take a lot of time and effort to implement. So I think it's important to have a good discussion on this first.

Both the chaining and piping approaches have their pros and cons. I am personally leaning towards the chaining approach because I think it's easier to reason about and does not suffer as much from keyword naming conflicts. On the other hand, last week I leaned more towards the piping approach because it feels like it belongs more in the existing language and way of thinking.

Relevant existing proposals

Please let me know if I missed any existing relevant proposals

Activity

  1. pekkaklarck commented on Nov 10, 2026

    @pekkaklarck
    Member

    This is an interesting syntax idea and I can see that in some scenarios it would make tests/tasks simpler. Another benefit would be that the initial set of keywords in a library could be smaller, because the returned items would implement more keywords. That could also simplify library implementation. I also like the proposed -> syntax (at least C++ uses it as well), but alternatives can certainly be proposed.

    There are some design decisions to be made:

    1. Do we want to allow using -> below a keyword call without the ... line continuation like in the description does? I think that makes sense because ... -> would look strange.
    2. If we support the above, then -> can in the future appear in the place where you currently can only have a keyword name. We don't restrict keyword names, so someone may have created such a keyword and this syntax would break such usages. I don't consider that a showstopper, but we probably should deprecate keywords with name -> in RF 7.6 and then implement this earliest in RF 8.0.
    3. Do we also want to allow chaining on a single line like Keyword 1 -> Keyword 2? That could be convenient in simple cases.
    4. If we support single line chaining, this syntax breaks cases where -> is used as an argument. Such usages are most likely rare and escaping like \-> would work. This still makes the case for single line chaining a little weaker in my opinion.
    5. How should Libdoc collect this information? It certainly cannot execute all keywords a library provides to find out do the return values implement more keywords. One idea is using return type hints. Possibly the types should also be decorated with something like @sublibrary to be recognized. This is a pretty important thing to be designed and decided.
    6. How should Libdoc show this information in the UI and store in its spec files?
    7. Should Robot at runtime check is the returned item a @sublibrary or should it just try to find a matching keyword when the -> syntax is used? I believe no extra checking is needed.
    8. Should sub-libraries (or child-libraries, we need a good name for these) support also the dynamic API? I think that would make sense for consistency and probably this wouldn't complicate the implementation either.
    9. What if -> xxx doesn't match a keyword but instead there's an attribute with name xxx? Should that be an error or should we return the attribute value? I can see usages for the latter, but I also see that this could lead to strange problems. It's probably better to make this an error
  2. pekkaklarck commented on Nov 13, 2026

    @pekkaklarck
    Member

    If we agree that this is a good idea and also agree on the syntax, then there would be more design decisions to be made related to modeling these chains internally. In this comment I cover ideas how to represent chains in the parsing model, but we also needed to think how to represent them in the execution data model, in the result model and in the log file.

    If you have a keyword call like

    ${request} =    POST    https://example.com
    

    the result in the parsing model is a KeywordCall node like this:

    KeywordCall(
        type='KEYWORD',
        tokens=(
            Token(SEPARATOR, '    ', 4, 0),
            Token(ASSIGN, '${request} =', 4, 4),
            Token(SEPARATOR, '    ', 4, 16),
            Token(KEYWORD, 'POST', 4, 20),
            Token(SEPARATOR, '    ', 4, 24),
            Token(ARGUMENT, 'https://example.com', 4, 28),
            Token(EOL, '\n', 4, 47)
        ),
        lineno=4,
        col_offset=0,
        end_lineno=4, 
        end_col_offset=48, 
        errors=()
    )

    If we wanted to support

    ${request} =    POST    https://example.com
    ->  Add Header    Authorization    Bearer 923u49ujjidashuihdc8923yh98rhjd2
    

    the result could be a new node (e.g. KeywordChain) that has KeywordCall nodes as its children. Something like this:

    KeywordChain(
        statements=[
            KeywordCall(...),
            KeywordCall(...)
        ],
        ...
    )

    I'm not sure should possible assignment be part of the KeywordChain or is it fine to have it as part of the first KeywordCall. The new -> marker should get its own token type, but that's a simple addition.

    Another alternative would be that the first keyword call could get an attribute like chain that points to the chained keyword call, recursively, or None when there's no chain. Something like this:

    KeywordCall(
        ...,
        chain=KeywordCall(...)
    )

    This latter approach would be easier to parse. We could parse the initial statement normally and just add a chain if there's ->. The former model looks somewhat nicer, but we already represent IF and TRY structures the same way with attributes orelse and next, respectively.

  3. Lakitna commented on Nov 26, 2026

    @Lakitna
    Author

    Do we want to allow using -> below a keyword call without the ... line continuation like in the description does? I think that makes sense because ... -> would look strange.

    I prefer the bare -> over ... ->. The second version makes -> look like an argument instead of a language feature.

    Do we also want to allow chaining on a single line like Keyword 1 -> Keyword 2? That could be convenient in simple cases.

    In my opinion: Yes. It would be convenient and conceptually easy to understand: -> is always a chaining operation.

    If we support single line chaining, this syntax breaks cases where -> is used as an argument. Such usages are most likely rare and escaping like -> would work. This still makes the case for single line chaining a little weaker in my opinion.

    Can this be handled similarly to the -> keyword variant? "deprecate keywords with name -> in RF 7.6 and then implement this earliest in RF 8.0."

    How should Libdoc collect this information? It certainly cannot execute all keywords a library provides to find out do the return values implement more keywords. One idea is using return type hints. Possibly the types should also be decorated with something like @sublibrary to be recognized. This is a pretty important thing to be designed and decided.

    If I made a library with chaining keywords, I would ensure that the return values of my parent library are all typed. Libdoc can use this type to discover the sublibrary and its keywords. It may not even need the @sublibrary decorator to discover this. Though I also like the decorator for clarity reasons.

    I would be ok with libdoc not knowing about the subkeyword when I don't type the return value of the parent keyword. I would also be ok with having one and only one accepted way of writing these things. It's and advanced feature to implement, I don't think it needs the same flexibility that a regular library needs.

    How should Libdoc show this information in the UI and store in its spec files?

    Excellent question, may need a separate thread? Since it's such a different type of discussion.

    Should Robot at runtime check is the returned item a @sublibrary or should it just try to find a matching keyword when the -> syntax is used? I believe no extra checking is needed.

    I would make the runtime check the existence of the chained keyword on the given variable. If the variable is not a sublibrary, this check will fail. This also means that runtime checking is kept to "can I find this keyword", so it's kept computationally minimal. This does open up some potentially tricky ways of writing library code to hook into this part of core though.

    I think the most important part is to keep it simple. If @sublibrary detection makes it simpler, let's do that. If it doesn't need it, let's not. As I said in an earlier point, it's and advanced feature to implement.

    What if -> xxx doesn't match a keyword but instead there's an attribute with name xxx? Should that be an error or should we return the attribute value? I can see usages for the latter, but I also see that this could lead to strange problems. It's probably better to make this an error

    I think it should be an error. -> should be keyword only. Getting an attribute from a class instance is a different matter that is already very solvable with Evaluate, ${variable.attribute}, etc. I think it doesn't need to be folded into this syntax. If you really want something, I'd prefer dedicated syntax for attributes instead of piggybacking of keyword chaining.


    @bhirsz Do you have an opinion on Pekka's model suggestions? I can forsee quite a few useful RoboCop rules for a feature like this, so making parsing it easy would be great :)


    Unrelated note: I almost tagged the Github user SubLibrary :')

  4. bhirsz commented on Nov 26, 2026

    @bhirsz
    Contributor

    As for model, what about using similiar approach like if else branches - so attribute pointing to next keyword in chain?

    KeywordCall(
    tokens=...,
    chain=KeywordCall()
    )

    Though it doesnt really matter for me. We could wrap it similiar as group or any other block.

    Edit - now I see the exact syntax proposed already by Pekka. I am in the train and I skimmed through. I will re-read it properly in few days

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions