[英]Python function with more than one return (many returns problem)
在我学习 Python 期间,我读到不建议一个函数有多个返回。 例如,这是我下面的函数:
def get_hero_names_from_database(id: int) -> dict:
hero_names = {}
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute(get_names_query, (id,))
names = cursor.fetchall()
for name in names:
hero_names = {
"name": name[0],
"localized_name": name[1]
}
except mysql.connector.Error as error:
print("Failed to select hero names: {}".format(error))
finally:
cursor.close()
close_connection(connection)
# Check if select return is empty, that's it don't have hero with this ID.
if hero_names:
return hero_names
else:
print("There is no hero with this ID.")
该函数通过 ID 从我的数据库中获取某个英雄的名称,然后将所有这些转换为字典,但是,当我传递一个不存在的 ID 时,我的字典将为空,因为我的数据库不会返回任何内容。 到目前为止一切顺利,我什至创造了一个条件来解决这个问题:
# Check if select return is empty, that's it don't have hero with this ID.
if hero_names:
return hero_names
else:
print("There is no hero with this ID.")
笔记:
问题是,当我的字典为空时,上述条件将返回None ,正如我在帖子开头所说的那样,不建议 Python 函数有多个返回。
知道这一点后,我修改了条件以在字典为空时创建异常:
# Check if select return is empty, that's it don't have hero with this ID.
if not hero_names:
raise ValueError("There is no hero with this ID.")
else:
return hero_names
好的,现在我有一个空字典时看起来像这样的异常:
Traceback (most recent call last):
File "dota2learning/database.py", line 107, in <module>
hero_names = get_hero_names_from_database(500)
File "dota2learning/database.py", line 94, in get_hero_names_from_database
raise ValueError("There is no hero with this ID.")
ValueError: There is no hero with this ID.
现在我有以下问题:
如何测试此输出,因为我在下面创建了断言但它不起作用:
@pytest.mark.get_names
def test_get_hero_names_from_database_invalid_id():
# Test the console return when pass invalid id, that's, no hero with this ID.
result = get_hero_names_from_database(500)
assert result == "There is no hero with this ID."
我只是为了测试而通过了一个无效的 ID,但我无法通过这个测试:
# Check if select return is empty, that's it don't have hero with this ID.
if not hero_names:
> raise ValueError("There is no hero with this ID.")
E ValueError: There is no hero with this ID.
dota2learning\database.py:94: ValueError
====================== short test summary info ======================
FAILED tests/database/test_database.py::test_get_hero_names_from_database_invalid_id - ValueError: There is no hero with this ID.
====================== 1 failed, 3 passed in 0.72s ==================
笔记:
最后,确实建议避免函数返回不期望的值,例如None ?
当没有可以返回的值时返回None
通常是可以接受的。 如果您调用该函数并打印结果,则在 ID 不匹配时获取None
具有直观意义,因为没有具有该 ID 的英雄,因此应该没有信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.