是否有编写get_or_create
方法的标准化方法。例如,要创建新客户:
get_or_create_customer(email='hello@example.com')
我见过这样的方法,要么返回None
,返回<item>
,要么返回一个元组,说明除了该项目外是否还创建了该项目(如django的get_or_create), (True, <item>)
。
在get_or_create
方法中返回值有建议的做法吗?
答案 0 :(得分:0)
按照您的示例,我的方法是:
#Returns a tuple where the first item is "False" if the email already exists in database,
#and "True" if it doesn't and it was appended to the database. The second item is the email.
def get_or_create_customer (email , database): #email as String, database as list
if email in database:
return (False, email)
else:
database.append(email)
return (True, email)
测试代码:
database = ["hello@gmail.com"]
print (get_or_create_customer("hello@gmail.com", database), database)
>> (False, 'hello@gmail.com') ['hello@gmail.com']
print (get_or_create_customer("example@gmail.com", database), database)
>> (True, 'example@gmail.com') ['hello@gmail.com', 'example@gmail.com']