简体   繁体   English

具有多个返回的 Python 函数(许多返回问题)

[英]Python function with more than one return (many returns problem)

during my studies on Python I read that it is not recommended a function to have more than one return.在我学习 Python 期间,我读到不建议一个函数有多个返回。 For example, this my function below:例如,这是我下面的函数:

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.")

The function takes names of a certain hero by ID from my Database and then transforms all this into a dictionary, however, when I pass an ID that does not exist, my dictionary will be empty since my Database will not return nothing.该函数通过 ID 从我的数据库中获取某个英雄的名称,然后将所有这些转换为字典,但是,当我传递一个不存在的 ID 时,我的字典将为空,因为我的数据库不会返回任何内容。 So far so good, I even create a condition to solve this problem:到目前为止一切顺利,我什至创造了一个条件来解决这个问题:

# 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.")

NOTE:笔记:
The problem is that the above condition will return a None when my dictionary is empty and as I said at the beginning of the post it is not recommended for a Python function to have more than one return.问题是,当我的字典为空时,上述条件将返回None ,正如我在帖子开头所说的那样,不建议 Python 函数有多个返回。

Knowing this I modified my condition to create an exception when my dictionary is empty:知道这一点后,我修改了条件以在字典为空时创建异常:

# 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

Okay, now I have an exception that looks something like this when I have an empty dictionary:好的,现在我有一个空字典时看起来像这样的异常:

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.

Now I have the following questions:现在我有以下问题:

  • Is this output without much formatting normal?这个没有太多格式化的输出正常吗?
    • I just wanted to see "There is no hero with this ID."我只是想看看“没有这个ID的英雄”。

How do I test this output, because I created the assert below and it didn't work:如何测试此输出,因为我在下面创建了断言但它不起作用:

@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."

I passed an invalid ID just to test and I can't get this test to pass:我只是为了测试而通过了一个无效的 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 ==================

NOTE:笔记:
Finally, it is really recommended to avoid that a function returns a value that is not expected, for example None ?最后,确实建议避免函数返回不期望的值,例如None ?

Returning None when there is no value that can be returned is usually acceptable.当没有可以返回的值时返回None通常是可以接受的。 If you call the function, and print the results, getting None when the ID has no match makes intuitive sense as there was no hero with that ID so there should be no information.如果您调用该函数并打印结果,则在 ID 不匹配时获取None具有直观意义,因为没有具有该 ID 的英雄,因此应该没有信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM