Created
July 31, 2012 15:18
-
-
Save aaronlevin/3217751 to your computer and use it in GitHub Desktop.
(potentially bad) Example of decorator defined as class method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Density(object): | |
def __init__(self, data, bw=None): | |
""" class definitions | |
""" | |
self.maxmin['maxima'] = [] | |
self.maxmin['minima'] = [] | |
def new_values_for_maxmin_validator(method): | |
"""This is the decorator | |
""" | |
def wrapper(self, *args, **kwargs): | |
if self.new_values is None: | |
raise ValueError('Max/Min cannot be calculated until density values have been calculated.') | |
else: | |
if self.new_values: | |
# Reassign maxima / minima values | |
self.maxmin['maxima'] = [] | |
self.maxmin['minima'] = [] | |
# Logic to calculate self.maxmin | |
return method(self, *args, **kwargs) | |
return wrapper | |
@property | |
@new_values_for_maxmin_validator | |
def maxima(self): | |
return self.maxmin['maxima'] | |
@property | |
@new_values_for_maxmin_validator | |
def minima(self): | |
return self.maxmin['minima'] |
As commented on SO, I don't think this is bad. I'd move the decorator out of the class scope since I don't feel it belongs there – accessing a.new_values_for_maxmin_validator()
for a Density
instance a
does not make any sense.
@smarnach It should remain in the class scope since the wrapper references instance specific attribute (self.new_values
, self.maxmin
), so it makes zero sense if the closure is not associated with that specific class.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this bad? It seems like it is potentially bad. But, how else to do this?