My python code is ugly and I'm having difficulty improving it. What kind of steps could be done here to make it. This is an example function that comes from time to time and I can't seem to have a good way to pick it up. The re.match for me is a mess. The creation of variables that have negative values like 'created = False' 'option_id = None' makes me shiver at night, also how to avoid the 'if value:' that pushes all the function to the right. I'm in need of a zen teaching:
def get_id(string):
try:
match = re.match('^[\w_]+?_(\d+)$', string).groups()
except:
return None
return match[0]
def admin_add_detail_option(request, detail_id, value):
created = False
option_id = None
if value:
detail_id = get_id(detail_id)
try:
detail = Detail.objects.get(id=detail_id)
except Detail.DoesNotExist:
pass
else:
option, created = DetailOption.objects.get_or_create(name=value, detail=detail)
option_id = option.id
return simplejson.dumps({'created':created, 'id':option_id, 'name':detail_id, 'text':value})
Thank you
After reading Bruno post this was re-factored to:
def get_id(string):
match = re.match('^[\w_]+?_(\d+)$', string)
if match
return match.groups()[0]
return None
def admin_add_detail_option(label, text):
result = {'created':False, 'id':None, 'name':label, 'text':text}
if not text:
return simplejson.dumps(result)
detail_id = get_id(label)
try:
option, created = DetailOption.objects.get_or_create(name=text, detail__id=detail_id)
except Detail.DoesNotExist:
pass
else:
result.update({'created':created, 'id':option_id})
return simplejson.dumps(result)
I hope I understood all of your point has they have been very helpful.
Thank you.