我遇到了一个似乎无法解决的有趣问题。我有一个非常复杂的系统调用格式化工具,它被定义为我们支持的每种格式的类。类名是动态确定的,并且值的格式基于客户端的API POST文档。
我遇到的问题是某些值需要单个键/值对(key, value)
,而有些值需要多对,我将其放入元组[(key1, value1), (key2, value2)]
列表中。
我需要做的是获取密钥/值(s)并创建一个元组元组并将其传递以进行传递。我不能使用字典,因为后来的命令可能很重要。
这段代码的整体结构非常庞大,所以为了便于阅读,我会尝试将其分解成小块。
calling_function:
def map_lead(self, lead):
mapto_data = tuple()
for offer_field in self.offerfield_set.all():
field_name = offer_field.field.name
if field_name not in lead.data:
raise LeadMissingField(lead, field_name)
formatted_list = format_value(offer_field.mapto, lead.data[field_name])
if type(formatted_list).__name__ == 'list':
for item in formatted_list:
mapto_data += (item,)
elif type(formatted_list).__name__ == 'tuple':
mapto_data += (formatted_list)
return mapto_data
example_format_type1:
@staticmethod
def do_format(key, value):
area_code, exchange, number = PhoneFormat.format_phone(value)
return [
(PhoneFormat.AREA_CODE_MAPTO, area_code),
(PhoneFormat.PHONE_EXCHANGE_MAPTO, exchange),
(PhoneFormat.VANTAGE_MEDIA_HOME_PHONE_NUMBER_MAPTO, number)
]
example_format_type2:
@staticmethod
def do_format(key, value):
if len(value) > 3:
value = value[:3] + '-' + value[3:]
if len(value) > 7:
value = value[:7] + '-' + value[7:]
return key, value
我试图明确定义example_format_type2
的返回值为元组:
@staticmethod
def do_format(key, value):
if len(value) > 3:
value = value[:3] + '-' + value[3:]
if len(value) > 7:
value = value[:7] + '-' + value[7:]
formatted_value = tuple()
formatted_value += (key, value)
return formatted_value
但似乎无论我做什么,它都被解释为calling_function
中的列表。
所以,我总是得到type(formatted_list).__name__ == 'list'
。因此,如果它是一个元组,我将返回for
循环遍历元组中的每个项目,并将其作为mapto_data
元组中的单个值添加。
有没有办法强制Python从example_format_type2
返回值,以便在calling_function
中将其解释为元组?
EDIT1:
事实证明问题发生在我map_lead
元组的mapto_data
中。我错过了那里的尾随逗号。
答案 0 :(得分:1)
我相信你可以只返回一个元组文字(idk,如果这就是它的名字)?
>>> def test():
... return (1, 2)
...
>>> thing = test()
>>> thing
(1, 2)
>>> type(thing)
<type 'tuple'>
>>> type(thing).__name__
'tuple'
答案 1 :(得分:0)
example_format_type2
会返回一个元组,我很确定错误是在其他地方。就像format_value
函数一样。请注意,如果您使用+ =将元组添加到列表中,结果将是一个列表:
>>> a = [1, 2]
>>> a += (3, 4)
>>> print a
[1, 2, 3, 4]
还要考虑使用以下语法检查formatted_list
的类型:
if type(formatted_list) is tuple:
...