I need to decorate dynamically a getter and setter pair methods in a subclass using/mimic the syntactic sugar syntax.
I am struggling with the setter implementation.
class A:
def __init__(self, x):
print('init')
self.__x = x
@property
def x(self):
print('getter')
return self.__x
@x.setter
def x(self, v):
print('setter')
self.__x = v
class Dec:
def __init__(self):
print('init - dec')
def __call__(self, cls):
c = type('A_Dec', (cls,), {})
# super-init
setattr(c, '__init__', lambda sub_self, x: super(type(sub_self), sub_self).__init__(x))
# getter
setattr(c, 'x', property(lambda sub_self: super(type(sub_self), sub_self).x))
# setter - see below
return c
dec_A = Dec()(A)
dec_a = dec_A('p')
print(dec_a.x)
Output
init - dec
init
getter
p
If I try to implement the setter method in Dec
, dec_a.x = 'p'
, with the following methods I collect the following errors:
# setter-statements of __call__
# Attempt 1
setattr(c, 'x', property(fset=lambda sub_self, v: super(type(sub_self), sub_self).x(v)))
# AttributeError: unreadable attribute
# Attempt 2 - auxiliary function
def m(sub_self, v):
print('--> ', sf, super(type(sub_self), sub_self))
super(type(sub_self), sub_self).x = v
# Attempt 2.A
setattr(c, 'x', eval('x.setter(m)'))
# NameError: name 'x' is not defined
# Attempt 2.B
setattr(c, 'x', property(fset=lambda sf, v: m(sf, v)))
# AttributeError: unreadable attribute
# Attempt 2.C: !! both at once, `fget`and `fset` so, in case, comment the getter in the above code to avoid conflicts
setattr(c, 'x', property(fget=lambda sub_self: super(type(sub_self), sub_self).x, fset=m))
# AttributeError: 'super' object has no attribute 'x'
# Attempt 2.D
p = property(fget=lambda sub_self: super(type(sub_self), sub_self).x, fset=m)
setattr(c, 'x', p)
# AttributeError: 'super' object has no attribute 'x'
Attempt 1 raises an error because (I guess) setting the attribute with brackets. So in Attempt 2 I make use of an auxiliary function, since lambda
doesn't allow initialization , '=' statements, again with no success.
Is there a way to mimic the property getter/setter decorators dynamically? (Possibly without extra imports) Is there another way to do it?
Extra: why super doesn't work without attributes?
super().x(v)
->TypeError: super(type, obj): obj must be an instance or subtype of type
EDIT:
- Answer of Extra: from the doc: The zero argument form only works inside a class definition[...]
- working with python3.9