0

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)

jay
  • 493
  • 1
  • 3
  • 11
  • This seems like overkill. `if not isinstance(value, str): raise ValueError("String values only")`. – chepner Apr 17 '23 at 21:47
  • In this context, it's overkill, but I've only provided a MWE. Single dispatch can be much more eloquent when you have more than a type or two to parse. Your argument is an anti-pattern against *all* uses of single dispatch. – jay Apr 17 '23 at 22:56

0 Answers0