我想创建一个类型注释来描述必须是 class和 classT的子类的类型。AB
T = TypeVar('T', bound=A)仅指定T必须是 的子类A。
T = TypeVar('T', A, B)仅指定T必须是子类A或子类B但不一定是两者。
我实际上想要类似的东西T = TypeVar('T', bound=[A, B]),这意味着T必须对A和进行子类化B。有这样做的标准方法吗?
我有以下用于连接 Postgres 数据库的代码:
func connectToPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) {
var err error
for i := 0; i < 5; i++ {
p, err := pgxpool.Connect(ctx, url)
if err != nil || p == nil {
time.Sleep(3 * time.Second)
continue
}
log.Printf("pool returned from connect: %s", p)
return p, nil
}
return nil, errors.Wrap(err, "timed out waiting to connect postgres")
}
Run Code Online (Sandbox Code Playgroud)
用例是在使用 docker-compose 启动我的服务器时等待 Postgres 变得可用。即使代码休眠 if p == nil,第一个返回之前的日志也会打印出来:pool returned from connect: %!s(*pgxpool.Pool=<nil>)
有什么办法pgxpool可以让后台进程实现 …
假设我有以下内容:
from __future__ import annotations
class A(object):
@classmethod
def some_class_method(cls: ?, parameter: str) -> ?:
return A
Run Code Online (Sandbox Code Playgroud)
?如果我想明确表示some_class_method返回的是 classA而不是class的实例,应该怎么办A。
编辑:@chepner提出了一个很好的点在?可能是指以A或的任何子类A。