超载提示方式:5.3

2024-04-20 02:13:19 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我现在误解了这个功能。It's not designed for multiple dispatch

NOTE: While it would be possible to provide a multiple dispatch implementation using this syntax, its implementation would require using sys._getframe() , which is frowned upon. Also, designing and implementing an efficient multiple dispatch mechanism is hard, which is why previous attempts were abandoned in favor of functools.singledispatch() . (See PEP 443 , especially its section "Alternative approaches".) In the future we may come up with a satisfactory multiple dispatch design, but we don't want such a design to be constrained by the overloading syntax defined for type hints in stub files. It is also possible that both features will develop independent from each other (since overloading in the type checker has different use cases and requirements than multiple dispatch at runtime -- e.g. the latter is unlikely to support generic types).

===

我在Java领域已经有一段时间了,我将返回Python3.5。我想使用新的类型提示功能,但是方法重载有问题。从我对这个特性的理解来看,这应该得到支持。在

下面是我正在学习的一个小课程:

授权.pyi(注意pyi)

import typing
import gitlab


class LicensingChecker(object):
    @typing.overload
    def __init__(self, url: str, api_key: str) -> None: ...
    @typing.overload
    def __init__(self, gl: gitlab.Gitlab) -> None: ...

    def iter_projects(self) -> typing.Iterator[str]: ...

授权.py

^{pr2}$

这是一个玩具的例子,但这个想法相当传统。我提供了两个构造函数,一个接受已经存在的gitlab客户机,另一个将实例化它。(这个脚本不需要双重构造函数,但是我看到了@typing.overload,想看看它是如何工作的。)

Pycharm和Cpython似乎对这段代码很满意,但是第一个构造函数是不可访问的——比如@typing.overloaddecorator不能工作:

>>> import gitlab
>>> import licensing
>>> licensing.LicenseChecker(gitlab.Gitlab('https://blah.blah.blah/gitlab', 'hunter2'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'api_key'

我有什么特别的事要做才能让超负荷工作吗?目前,我只是调用内置的REPL或ipython。在


Tags: thetoinimportselftypinginitis
1条回答
网友
1楼 · 发布于 2024-04-20 02:13:19

非类型化Python不支持重载。您的第二个__init__正在覆盖第一个,因此出现错误。您需要编写一个带有运行时类型检查的__init__

def __init__(self, arg1, arg2=None):
    if isinstance(arg1, gitlab.Gitlab) and arg2 is None:
        self.gl = arg1
    elif arg1 is not None and arg2 is not None:
        self.gl = gitlab.Gitlab(arg1, arg2)
    else:
        raise TypeError('........')

(有一个^{}可以用一个参数改变类型来模拟重载,但它不适合您的情况)


@typing.overload修饰符只是告诉类型检查器可以有多个参数组合,但这并不意味着您现在可以用相同名称在两个不同的函数中编写实现。从PEP 484

Uses of the @overload decorator as shown above are suitable for stub files. In regular modules, a series of @overload-decorated definitions must be followed by exactly one non-@overload-decorated definition (for the same function/method). The @overload-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload-decorated definition, while the latter is used at runtime but should be ignored by a type checker.

相关问题 更多 >