HTML id attribute for components

Playwright sounds like they have the right approach! An attribute is much less disruptive than requiring an ID.

As a general point of style, “monkey-patching” like some of the examples in this thread (ie adding extra properties and things to system classes to do what you want) is something the Python community discourages. It’s brittle, because it could break (or cause mysterious breakages in your code) when we update the inner workings of the Component class. It’s also harder for readers of your code to understand (in this case, they’ll look at the property, go “wait, that’s not built in on all Anvil components, is it?”, try it in their own code, get frustrated, and eventually search over your whole code-base to find the form whose __init__ method installed the monkey patch!).

Instead, the Pythonic way to do it is to use a function. For example, you could put this in a module called TestHooks:

from anvil.js import get_dom_node

def set_test_id(component, test_id):
    get_dom_node(component).setAttribute("data-testid", test_id)

Then in your forms, it’s no more lines of code than your version:

from TestHooks import set_test_id
# ...

class Something(SomethingTemplate):
    def __init__(self, **properties):
        # ...
        set_test_id(self.your_component, "Something to search by")

Just as simple, but much easier for someone else to read – and much less fragile when we update the Component class!

4 Likes