Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何处理静态类型语言中的各种错误(或在一般情况下键入时)_Python_C++_Typing_Static Typing - Fatal编程技术网

Python 如何处理静态类型语言中的各种错误(或在一般情况下键入时)

Python 如何处理静态类型语言中的各种错误(或在一般情况下键入时),python,c++,typing,static-typing,Python,C++,Typing,Static Typing,对于上下文,我的主要语言是Python,我刚刚开始使用注释。这是为学习C++准备的(而且因为直觉上,感觉更好)。 我有这样的想法: from models import UserLocation from typing import Optional import cluster_module import db def get_user_location(user_id: int, data: list) -> Optional[UserLocation]: loc = Use

对于上下文,我的主要语言是Python,我刚刚开始使用注释。这是为学习C++准备的(而且因为直觉上,感觉更好)。
我有这样的想法:

from models import UserLocation
from typing import Optional
import cluster_module
import db
def get_user_location(user_id: int, data: list) -> Optional[UserLocation]:
    loc = UserLocation.query.filter_by(user_id=user_id).one_or_none()
    if loc:
        return loc
    try:
        clusters = cluster_module.cluster(data)
    except ValueError:
        return None # cluster throws an error if there is not enough data to cluster

    if list(clusters.keys()) == [-1]:
        return None # If there is enough data to cluster, the cluster with an index of -1 represents all data that didn't fit into a cluster. It's possible for NO data to fit into a cluster.
    loc = UserLocation(user_id=user_id, location = clusters[0].center)
    db.session.add(loc)
    db.session.commit()
    return loc
因此,我使用
typing.Optional
,以确保在出现错误时可以返回
None
(如果我理解正确,与此等效的静态类型语言将返回相应类型的空指针)。但是,如何区分这两个错误呢?例如,我想做的是,如果没有足够的数据进行聚类,则返回
-1
,如果有数据,则返回
-2
,但这些数据都不适合聚类(或类似的事情)。在Python中,这非常简单(因为它不是静态类型)。即使使用
mypy
,我也可以说类似于
键入.Union[UserLocation,int]

<>但是,如何在C++或java中实现这一点呢?Java程序员是否需要将函数设置为返回
int
,并返回
UserLocation
的ID而不是对象本身(那么,使用
get\u user\u location
函数的任何代码本身都会进行查找)?这样做是否有运行时的好处,或者只是重新构造代码以适应语言是静态类型的这一事实

我相信我了解静态类型w.r.t.代码可读性、编译时和运行时效率的大部分明显好处,但我不确定如何处理这个特殊问题


简而言之:如何处理函数(返回非基本类型),表明它们在静态类型语言中遇到了不同的错误?

< P>与Python解决方案等价的直接C++将是<代码> STD::变体< /C> >其中代码> T 是预期返回值,<代码> U/COD>错误代码类型。然后,您可以检查变量包含哪些类型,并从中开始。例如:

#include <cstdlib>
#include <iostream>
#include <string>
#include <variant>

using t_error_code = int;

// Might return either `std::string` OR `t_error_code`
std::variant<std::string, t_error_code> foo()
{
    // This would cause a `t_error_code` to be returned
    //return 10;

    // This causes an `std::string` to be returned
    return "Hello, World!";
}

int main()
{
    auto result = foo();

    // Similar to the Python `if isinstance(result, t_error_code)`
    if (std::holds_alternative<t_error_code>(result))
    {
        const auto error_code = std::get<t_error_code>(result);
        std::cout << "error " << error_code << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << std::get<std::string>(result) << std::endl;
}
#包括
#包括
#包括
#包括
使用t_error_code=int;
//可能返回'std::string'或't_error_code'`
std::variant foo()
{
//这将导致返回't_error_code'
//返回10;
//这将导致返回一个'std::string'
返回“你好,世界!”;
}
int main()
{
自动结果=foo();
//类似于Python'if-isinstance(result,t\u error\u代码)`
如果(std::holds_备选方案(结果))
{
const auto error_code=std::get(结果);

STD::CUT< P>与Python解决方案等价的直接C++将是:ST::变体其中代码“>t/CODE”是预期返回值,<>代码> U/COD>错误代码类型。然后,可以检查变量包含的类型中的哪一个并从那里开始。例如:

#include <cstdlib>
#include <iostream>
#include <string>
#include <variant>

using t_error_code = int;

// Might return either `std::string` OR `t_error_code`
std::variant<std::string, t_error_code> foo()
{
    // This would cause a `t_error_code` to be returned
    //return 10;

    // This causes an `std::string` to be returned
    return "Hello, World!";
}

int main()
{
    auto result = foo();

    // Similar to the Python `if isinstance(result, t_error_code)`
    if (std::holds_alternative<t_error_code>(result))
    {
        const auto error_code = std::get<t_error_code>(result);
        std::cout << "error " << error_code << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << std::get<std::string>(result) << std::endl;
}
#包括
#包括
#包括
#包括
使用t_error_code=int;
//可能返回'std::string'或't_error_code'`
std::variant foo()
{
//这将导致返回't_error_code'
//返回10;
//这将导致返回一个'std::string'
返回“你好,世界!”;
}
int main()
{
自动结果=foo();
//类似于Python'if-isinstance(result,t\u error\u代码)`
如果(std::holds_备选方案(结果))
{
const auto error_code=std::get(结果);

STD::各种方法(“任何方法都适用”)。对于许多C++方法,你认为听起来像是需要例外而不是返回值。@弗兰·席伊安德里欧,在一个函数预期会失败的情况下,如何区分不同的情况/失败?(使用
std::variant
时会出现这种情况吗?@FrançoisAndrieux啊!太好了。谢谢。)如果你把你的评论写进一个答案中,我很乐意接受。我应该提到的是,你在某种程度上忘记了异常是错误处理机制之一。返回某种类型的
std::variant
std::optional
意味着调用方负责解包结果和检查有效值或报告d错误数据,这通常是不需要的。此外,您可能应该检查Ada/Spark作为一种正确的静态类型语言。C/C++是相当允许的。各种方式(~“任何一种方式都有效”)对于许多C++方法,你会看到声音像是需要异常而不是返回值。@弗兰·席伊斯安德里厄,在一个函数预期会失败的情况下,如何区分不同的情况/失败?(这是不是当使用代码> STD::变体< /代码>时的情况?)@FrançoisAndrieux啊!太好了。谢谢你。:)如果你把你的评论放在一个答案中,我很乐意接受。我应该提到的是,你在某种程度上忘记了异常是错误处理机制之一。返回某种
std::variant
std::optional
意味着调用方负责解包有效值或报告的错误数据的结果和检查,这通常是不需要的。此外,您可能应该检查Ada/Spark作为正确的静态类型语言。C/C++是相当允许的。