Skip to content

Instantly share code, notes, and snippets.

@aaronlevin
Created July 31, 2012 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronlevin/3217751 to your computer and use it in GitHub Desktop.
Save aaronlevin/3217751 to your computer and use it in GitHub Desktop.
(potentially bad) Example of decorator defined as class method
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']
@aaronlevin
Copy link
Author

Is this bad? It seems like it is potentially bad. But, how else to do this?

@smarnach
Copy link

smarnach commented Aug 1, 2012

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.

@cowbert
Copy link

cowbert commented Jan 9, 2018

@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