I have the following simple class and am wondering if there is a simple way to use a lambda, decorator, or helper method, etc... to avoid the duplicated for loop that appears in each method in CODENAMES and ALL_DEFAULTS?
class classproperty(object):
"""
When used to decorate a method in a class, that method will behave
like as a class property.
"""
def __init__(self, f):
# f - the func that's being decorated
self.f = f
def __get__(self, obj, cls):
# call the func on the class
return self.f(cls)
class PermissionInfo(object):
MODELS = ['ticket', 'person', 'role']
PERMS = ['view', 'add', 'change', 'delete']
@classproperty
def CODENAMES(cls):
codenames = []
for p in cls.PERMS:
for m in cls.MODELS:
codenames.append('{}_{}'.format(p, m))
return codenames
@classproperty
def ALL_DEFAULTS(cls):
ret = {}
for p in cls.PERMS:
for m in cls.MODELS:
ret["{}_{}".format(p, m)] = False
return ret
Duplicated for loop is this section of each method:
# ...
for p in cls.PERMS:
for m in cls.MODELS:
#...