Ellipsis
在Python中,一切皆对象,...是Ellipsis对象。
| 12
 3
 4
 
 | >>> ...Ellipsis
 >>> type(...)
 <class 'ellipsis'>
 
 | 
它是一个单例。
| 12
 3
 4
 
 | >>> id(...)4534353712
 >>> id(...)
 4534353712
 
 | 
作用
numpy中的切片操作
| 12
 3
 4
 
 | import numpy as np
 array = np.random.rand(2, 2, 2, 2)
 print(array[..., 0])
 
 | 
在上面的例子中,[:, :, :, 0] , [Ellipsis, 0]和[..., 0]是等价的。
类型提示
当函数中的参数允许任何类型时
下面的例子假定x的类型为Any
| 12
 3
 4
 5
 
 | def foo(x: ...) -> None:return x + x
 
 print(foo(2))
 print(foo("e"))
 
 | 
下面的例子假定func的参数为Any, 返回值为int
| 12
 3
 4
 5
 6
 
 | from typing import Callable
 def inject(func: Callable[..., int]) -> None:
 return func() + 5
 
 print(inject(lambda: 4))
 
 | 
当成pass用
当成参数默认值用
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | def foo(x=...):return x
 
 print(foo())
 print(foo(2))
 
 def bar(x=None):
 return x
 
 print(bar())
 print(bar(2))
 
 | 
Reference