数値を通貨としてフォーマットされた文字列にする

途中にとんでもないコードがあるけど気にすることはない

import locale, operator
def currencyformat(currency, i18n = False, conv = {}):
	localeconv = locale.localeconv()
	localeconv.update(conv)
	conv = localeconv

	cs = ((not i18n) and (conv['currency_symbol'], ) or (conv['int_curr_symbol'], ))[0]
	frac_digits = ((not i18n) and (conv['frac_digits'], ) or (conv['int_frac_digits'], ))[0]
	sign = ''
	sign_pos = 1
	cs_precedes = True
	sep_by_space = ''
	if currency >= 0:
		sign = conv['positive_sign']
		sign_pos = conv['p_sign_posn']
		cs_precedes = conv.get('p_cs_precedes', True)
		sep_by_space = conv.get('p_sep_by_space', False) and ' ' or ''
	else:
		sign = conv['negative_sign']
		sign_pos = conv['n_sign_posn']
		cs_precedes = conv.get('n_cs_precedes', True)
		sep_by_space = conv.get('n_sep_by_space', False) and ' ' or ''

	# not using conv['mon_grouping'] = [3, 0] (value is sample)
	currency = abs(currency)

	def grouping():
		w = 0
		for i, group_width in enumerate(conv['mon_grouping']):
			if group_width == locale.CHAR_MAX:
				w = 0
				break
			elif group_width == 0:
				break
			w = group_width
			yield w
		while True:
			yield w
	grouping = grouping()

	fraction = currency - int(currency)
	currency = reduce(operator.add, reversed(list(reduce(lambda i, j: i + ((j[0] != 0 and j[0] % 3 == 0) and conv['mon_thousands_sep'] or '') + j[1], enumerate(reversed(list(str(int(currency))))), ''))), '') + ((fraction != 0 and frac_digits > 0) and (conv['mon_decimal_point'] + ('%.*f' % (frac_digits, fraction, )).split('.')[1]) or '')

	#currency = locale.format("%.*f", (frac_digits, float(currency)), grouping = True).replace(',', conv['mon_thousands_sep']).replace('.', conv['mon_decimal_point'])

	# these are all patterns of formatted value.
	#(\1.1)
	#-\1.1
	#\-1.1
	#\1.1-
	#(1.1\)
	#-1.1\
	#1.1-\
	#1.1\-
	#-1.1 \
	#-\ 1.1
	#1.1 \-
	#\ 1.1-
	#\ -1.1
	#1.1- \
	#(\ 1.1)
	#(1.1 \)
	if sign_pos == 0:
		#(\1.1)
		#(1.1\)
		#(\ 1.1)
		#(1.1 \)
		if cs_precedes:
			currency = cs + sep_by_space + currency
		else:
			currency = currency + sep_by_space + cs
		currency = '(' + currency + ')'
	elif sign_pos == 1:
		#-\1.1
		#-1.1\ *1
		#-1.1 \ *2
		#-\ 1.1
		if cs_precedes:
			currency = cs + sep_by_space + currency
		else:
			currency = currency + sep_by_space + cs
		currency = sign + currency
	elif sign_pos == 2:
		#\1.1- *3
		#1.1\-
		#1.1 \-
		#\ 1.1- *4
		if cs_precedes:
			currency = cs + sep_by_space + currency
		else:
			currency = currency + sep_by_space + cs
		currency = currency + sign
	elif sign_pos == 3:
		#\-1.1
		#-1.1\ *1
		#-1.1 \ *2
		#\ -1.1
		if cs_precedes:
			currency = cs + sep_by_space + sign + currency
		else:
			currency = currency + sign + sep_by_space + cs
	elif sign_pos == 4:
		#\1.1- *3
		#1.1-\
		#\ 1.1- *4
		#1.1- \
		if cs_precedes:
			currency = cs + sep_by_space + currency + sign
		else:
			currency = currency + sign + sep_by_space + cs
	else:
		pass

	return currency