解決できないような興味深い問題に遭遇しました。私は、サポートする各フォーマットのクラスとして定義されているフォーマットツールを呼び出す非常に複雑なシステムを持っています。クラス名は動的に決定され、値はAPIPOSTに関するクライアントのドキュメントに基づいてフォーマットされます。
私が遭遇した問題は、いくつかの値が単一のキー/値のペア(key, value)
を必要とするのに対し、いくつかは複数のペアを必要とし、それをタプルのリストに入れること[(key1, value1), (key2, value2)]
です。
私がする必要があるのは、キー/値を取得し、タプルのタプルを作成して、配信のために渡すことです。後で順序が重要になる可能性があるため、辞書を使用できません。
このコードの全体的な構造は非常に広大なので、読みやすくするために細かく分割してみます。
call_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
。
タプルとしてexample_format_type2
解釈されるようにPythonに値を返すように強制する方法はありますか?calling_function
編集1:
問題は、タプルmap_lead
に追加していた場所にあることがわかりました。mapto_data
末尾のコンマを見逃しました。