3.3 Using Browser from Python
To create a custom Python library that uses the same Browser instance as your Robot Framework tests, you can fetch the already-imported Browser library instance from Robot Framework.
Important: avoid doing this in __init__.
Robot Framework tooling often instantiates (and introspects) libraries when generating keyword documentation and editor features. If your __init__ touches external resources (for example, expects a Browser/Playwright connection to exist), these tools can break.
This is why a lazily-evaluated cached_property is a good fit:
- LibDoc initializes the class to generate docs; if
__init__tries to access external resources, doc generation can fail. - RobotCode (code completion) also uses LibDoc-style introspection;
__init__gets executed just to discover keywords. - Keeping
__init__lightweight avoids unnecessary work when Robot Framework creates multiple instances even if no keyword is ever executed.
cached_property (from Python's standard library functools) computes the value once per instance on first access and then caches it on the object. Later accesses return the cached value.
@library
class CarConfigLibrary:
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_VERSION = VERSION
@cached_property
def b(self) -> Browser:
"""Return the already-imported Browser library instance.
Resolved lazily so LibDoc/RobotCode introspection does not require Browser/Playwright to be available.
"""
try:
return BuiltIn().get_library_instance("Browser")
except RuntimeError:
raise ImportError("You have to import the library 'Browser' as well.")
With this property (self.b), you can then access all Browser keywords directly.
Example:
@keyword
def login_user(self, user: str, password: str):
"""Login a User"""
self.b.type_text("#input_username", user)
self.b.type_text("#input_password", password)
self.b.click("#button_login")
See the example files.