Properties with single dispatch

104 views Asked by At

Is it possible to compose a property with singledispatch / singledispatchmethod features? I have tried the obvious patterns (nesting @singledispatchmethod with @prop.setter, etc) and get various errors. Here's a MWE of what I'd like to do, which only allows the property Foo.bar to be set to str values.

class Foo(object):
    
    def __init__(self):
        self._bar = 'baz'
    @property
    def bar(self):
        return self._bar
    @bar.setter
    def bar(self,value):
        self._bar = value
        @singledispatch
        def _set(value):
            raise NotImplementedError
        @_set.register(str)
        def _(value):
            return value
        try:
            self._bar = _set(value)
        except NotImplementedError:
            raise AttributeError(f"Can't set attribute 'bar' to type {type(value).__name__}")

One could, of course, rewrite singledispatch or property in order to facilitate this behavior. However, this seems like an obvious use case that should be a feature (now or eventually)

0

There are 0 answers