The patch()
and patch_to()
decorators from fastcore.basics
only create a getter method for a property. Setters and deleters are not supported.
I’d like to create a PR to add this functionality but it requires a change of the patch()
and patch_to()
signatures.
The current signatures are patch_to(cls, as_prop=False, cls_method=False)
and patch(f=None, *, as_prop=False, cls_method=False)
.
I’ve been considering:
patch_to(cls, as_prop=False, cls_method=False, name=None)
Where as_prop
can be a boolean or a string having one of the values “getter”, “setter”, “deleter”, boolean True being an alias for “getter”.
The argument name
allows one to use an attribute name that differs from the function names.
When name
is not used, the function name is used as the attribute name as in the current implementation.
I believe this approach has the least inpact on the current usage of patch
and patch_to
.
class Sample:
def __init__(self, v):
self.v = v
@patch_to(Sample, as_prop=True, name='val')
def get_v(self):
'''controlled access to v'''
return self.v
@patch_to(Sample, as_prop='setter', name='val')
def set_v(self, val):
self.v = val
@patch_to(Sample, as_prop='deleter', name='val')
def del_v(self):
self.v = None
s = Sample(10)
assert s.val == 10
s.val = 20
assert s.v == 20
del s.val
assert s.val is None
I welcome any comments on the proposed change.