traits icon indicating copy to clipboard operation
traits copied to clipboard

Observe mini-language: use "?" for optional traits

Open mdickinson opened this issue 2 years ago • 1 comments

Currently the observe machinery raises an exception when there's no trait matching the given name. For example, in

from traits.api import HasTraits, Instance, observe


class Foo(HasTraits):
    pass


class A(HasTraits):
    foo = Instance(Foo)

    @observe("foo:updated")
    def _do_something(self, event):
        pass


a = A()
a.foo = Foo()

the last line gives the error:

ValueError: Trait named 'updated' not found on <__main__.Foo object at 0x108b7cf90>.

This is valuable: it catches naming errors in observe mini-language strings. However, it's not always desirable.

Proposal: allow using observe("foo:updated?") to match updated if the trait exists, but not complain if it doesn't exist. This could be especially useful in combination with * in something like observe("*:updated?"), if we re-allow use of * in a non-terminal position.

mdickinson avatar Sep 20 '21 09:09 mdickinson

Worth noting for the discussion that this is not adding new functionality, just exposing something already implemented in the API. The current work-around is to do:

@observe(trait("foo").trait("updated", optional=True))
def _do_something(self, event):
    pass

corranwebster avatar Sep 20 '21 13:09 corranwebster