我正在尝试理解如何使用可选类型提示。从PEP-484,我知道我可以使用可选的def测试(a: int = None)作为def测试(a:联盟[int, None])或def测试(a:可选[int])。

但是下面的例子呢?

def test(a : dict = None):
    #print(a) ==> {'a': 1234}
    #or
    #print(a) ==> None

def test(a : list = None):
    #print(a) ==> [1,2,3,4, 'a', 'b']
    #or
    #print(a) ==> None

如果Optional[type]似乎意味着与Union[type, None]相同的事情,为什么我应该使用Optional[]呢?

我如何使用类型提示来注释一个函数,返回一个Iterable,总是产生两个值:bool和str?提示Tuple[bool, str]很接近,只是它将返回值类型限制为元组,而不是生成器或其他类型的可迭代对象。

我很好奇,因为我想注释一个函数foo(),它用于返回多个值,就像这样:

always_a_bool, always_a_str = foo()

通常像foo()这样的函数会做一些类似于return a, b(返回一个元组)的事情,但我希望类型提示足够灵活,可以用生成器或列表或其他东西替换返回的元组。

Python 3.5中谈论最多的特性之一是类型提示。

本文中提到了类型提示的一个例子,同时也提到了负责任地使用类型提示。谁能多解释一下它们,什么时候该用什么时候不该用?

假设我有一个函数:

def get_some_date(some_argument: int=None) -> %datetime_or_None%:
    if some_argument is not None and some_argument == 1:
        return datetime.utcnow()
    else:
        return None

我如何为可以为None的东西指定返回类型?

我正在尝试使用Python的类型注释和抽象基类来编写一些接口。是否有一种方法来注释*args和**kwargs的可能类型?

例如,如何表达一个函数的合理参数是一个整型或两个整型?type(args)给出元组,所以我的猜测是将类型注释为Union[Tuple[int, int], Tuple[int]],但这行不通。

from typing import Union, Tuple

def foo(*args: Union[Tuple[int, int], Tuple[int]]):
    try:
        i, j = args
        return i + j
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))

来自myypy的错误消息:

t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"

myypy不喜欢这个函数调用是有道理的,因为它期望在调用本身中有一个元组。unpacking后的添加也给出了一个我不理解的输入错误。

如何注释*args和**kwargs的敏感类型?

如何将变量的类型提示指定为函数类型?没有打字。函数,我在相关PEP PEP 483中找不到任何东西。

我在python中有一个函数,可以返回bool类型或列表类型。是否有一种方法可以使用类型提示指定返回类型?

例如,这是正确的方法吗?

def foo(id) -> list or bool:
    ...

如果我有一个这样的函数

def foo(name, opts={}):
  pass

我想给参数添加类型提示,怎么做呢?我假设的方式给了我一个语法错误:

def foo(name: str, opts={}: dict) -> str:
  pass

下面的语句不会抛出语法错误,但它似乎不是处理这种情况的直观方式:

def foo(name: str, opts: dict={}) -> str:
  pass

我在打字文档和谷歌搜索中都找不到任何东西。

编辑:我不知道Python中的默认参数是如何工作的,但为了解决这个问题,我将保留上面的示例。一般来说,最好做以下几点:

def foo(name: str, opts: dict=None) -> str:
  if not opts:
    opts={}
  pass

我在Python 3中有以下代码:

class Position:

    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

    def __add__(self, other: Position) -> Position:
        return Position(self.x + other.x, self.y + other.y)

但是我的编辑器(PyCharm)说引用位置不能解析(在__add__方法中)。我应该如何指定我期望返回类型为Position类型?

编辑:我认为这实际上是一个PyCharm问题。它实际上在警告和代码补全中使用了这些信息。

但如果我错了,请纠正我,并需要使用其他语法。