Python

Robot Framework Python: Install, Extend and Build Custom Libraries

Python-inspired shapes beside code brackets

Robot Framework Python integration is the reason the framework scales from simple checks to complex enterprise suites. The framework itself is written in Python, it installs with pip, and any Python module or class can become a keyword library, giving testers readable steps and developers full programming power.

How Robot Framework Relates to Python

Robot Framework is a Python package. The robot command is a small wrapper around the robot module, which means python -m robot works the same way and is handy when the command is not on PATH. Standard libraries such as BuiltIn and Collections are Python modules shipped with the package.

  • Installation happens through pip from PyPI
  • Keyword libraries are ordinary Python modules or classes
  • Variables can be loaded from Python variable files
  • Execution can be started programmatically through the robot API

Installing Into a Virtual Environment

A virtual environment keeps the framework and its libraries isolated per project. It also ensures that custom libraries import the same package versions locally and in CI, which avoids hard-to-explain differences between machines.

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
python -m pip install robotframework
pip freeze > requirements.txt

Committing a requirements file lets every teammate rebuild the same environment with pip install -r requirements.txt. Platform-specific details are covered in the installation walkthrough.

Writing a Custom Keyword Library

The simplest library is a Python module with functions. Each public function becomes a keyword, and its name is converted to a readable form, so order_total_should_be can be called as Order Total Should Be. Arguments map directly to function parameters.

# OrderLibrary.py
from robot.api.deco import keyword, library


@library
class OrderLibrary:

    @keyword("Order Total Should Be")
    def total_should_be(self, items, expected):
        total = sum(float(i) for i in items)
        if total != float(expected):
            raise AssertionError(f"Expected {expected}, got {total}")

A keyword fails when it raises an exception, and the exception message appears in log.html. Using AssertionError for verification failures is a clear convention that readers of the log will recognise immediately.

Using the Library in Test Data

Import the file with the Library setting. A relative path is resolved from the suite file, or you can install the library as a package and import it by module name.

*** Settings ***
Library    OrderLibrary.py

*** Test Cases ***
Total Is Correct
    @{items}=    Create List    10    20
    Order Total Should Be    ${items}    30

Library Decorators and Options

The robot.api.deco module provides decorators that control how methods become keywords. Using them makes a library explicit about which methods are keywords and how they are named, which keeps helper methods hidden from test data.

ToolWhat it does
@keywordMarks a method as a keyword and optionally sets a custom name or tags
@libraryConfigures the class, for example its scope and automatic keyword discovery
Type hintsLet the framework convert string arguments to integers, booleans and other types
DocstringsBecome keyword documentation when Libdoc generates library docs
robot.api.loggerWrites messages to log.html at different log levels

Argument Conversion With Type Hints

Values in test data are strings by default. When a keyword method declares type hints, the framework converts arguments before calling it, so count: int receives an integer and invalid input fails with a clear message instead of a confusing Python error deeper in the code.

@keyword
def wait_for_jobs(self, count: int, timeout: float = 10.0):
    ...

Python Variable Files

Variable files are Python modules whose module-level names become variables. They are useful for environment configuration, computed values and data that would be awkward in a Variables section. Load one with the Variables setting or the --variablefile option.

  • Keep URLs and credentials per environment in separate files
  • Generate dynamic values such as dates at import time
  • Share constants between Python libraries and test data

When to Move Logic Into Python

Test data is excellent for describing behaviour, but loops, string parsing and complex conditions quickly become hard to read in tabular form. A good rule is to keep tests focused on what is being verified and move how it is computed into a Python keyword.

  • Parsing files, JSON or database results
  • Calculations and data comparison with tolerances
  • Integrations with internal APIs or SDKs
  • Retry logic that needs fine-grained control

The resulting keywords stay readable in test data, which keeps suites approachable for non-programmers. See the Robot Framework keywords overview for how user keywords and library keywords work together.

Logging From Python Keywords

Messages written with the robot.api.logger module appear in log.html under the keyword that produced them. Using different levels keeps logs readable: informational messages for normal progress, debug messages for details and warnings for situations that need attention.

from robot.api import logger

logger.info("Fetched 12 orders")
logger.debug("Raw response received")
logger.warn("Retrying after timeout")

Run with --loglevel DEBUG to include debug messages in the log when investigating a failure.

Frequently Asked Questions

Which Python version does Robot Framework need?

Each release supports a specific range of Python 3 versions. Check the installation notes in the official repository or on PyPI for the release you plan to use before upgrading either one.

Can I run Robot Framework from a Python script?

Yes. The robot.run function accepts the same options as the command line and returns the exit code, which is useful for custom runners and tooling.

Are Python libraries the only way to extend the framework?

Python is the most common route. The remote library interface also lets keywords run in another process or language, and listeners can observe execution events.

Should libraries be classes or modules?

Both work. Modules suit simple stateless keywords, while classes are better when keywords share state such as connections, configuration or cached data across calls.

Can libraries keep state between tests?

Yes. The library scope setting controls whether a new instance is created for every test, every suite or once for the whole execution.

Keep the failure message part of the keyword's contract. A comparison keyword should report the expected value and the observed value in terms a suite author recognises. When testing the Python library, exercise an ordinary success, a failed assertion and an invalid argument. These cases expose errors in the library before they become difficult to trace across several Robot Framework suites. Where a keyword calls an external service, give that operation a deliberate timeout so a stalled request produces a diagnosis promptly.

Conclusion

Robot Framework Python integration gives each role the right tool: readable keywords for test design and real code for complex logic. Install in a virtual environment, start with a small library using the @keyword decorator, add type hints and document keywords with docstrings so Libdoc can publish them for the team.