如何创建自己的“参数化"广告素材?输入Python(例如"Optional [T]")吗? [英] How can I create my own "parameterized" type in Python (like `Optional[T]`)?

查看:90
本文介绍了如何创建自己的“参数化"广告素材?输入Python(例如"Optional [T]")吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中创建自己的参数化类型以用于类型提示:

I want to create my own parameterized type in Python for use in type hinting:

class MaybeWrapped:
    # magic goes here

T = TypeVar('T')

assert MaybeWrapped[T] == Union[T, Tuple[T]]

不要介意这个人为的例子;我该如何执行呢?我查看了Union和Optional的来源,但看起来我想避免一些相当底层的黑客.

Never mind the contrived example; how can I implement this? I looked at the source for Union and Optional, but it looks like some fairly low-level hackery that I'd like to avoid.

文档中的唯一建议来自示例的重新实现从通用继承的Mapping[KT,VT] .但是该示例更多地是关于__getitem__方法,而不是有关类本身.

The only suggestion in the documentation comes from an example re-implementation of Mapping[KT,VT] that inherits from Generic. But that example is more about the __getitem__ method than about the class itself.

推荐答案

如果您只是尝试创建通用类或函数,请尝试查看/rel =" nofollow noreferrer>文档–相当全面,比标准库键入文档还要详细.

If you're just trying to create generic classes or functions, try taking a look at the documentation on mypy-lang.org about generic types -- it's fairly comprehensive, and more detailed then the standard library typing docs.

如果您要实施自己的特定示例,则需要指出

If you're trying to implement your specific example, it's worth pointing out that type aliases work with typevars -- you can simply do:

from typing import Union, TypeVar, Tuple

T = TypeVar('T')

MaybeWrapped = Union[T, Tuple[T]]

def foo(x: int) -> MaybeWrapped[str]:
    if x % 2 == 0:
        return "hi"
    else:
        return ("bye",)

# When running mypy, the output of this line is:
# test.py:13: error: Revealed type is 'Union[builtins.str, Tuple[builtins.str]]'
reveal_type(foo(3))

但是,如果您试图用一种全新的语义来构造一个泛型类型,那么您很可能会走运.您剩余的选项是:

However, if you're trying to construct a generic type with genuinely new semantics, you're very likely out of luck. Your remaining options are to:

  1. 构造某种符合PEP 484的类型检查器 可以理解和使用的自定义类/元类内容.
  2. 以某种方式修改您正在使用的类型检查器(例如,mypy具有实验性的插件"系统)
  3. 请求修改PEP 484以包括您的新的自定义类型(您可以通过在键入模块仓库).
  1. Construct some kind of custom class/metaclass thing that PEP 484-compliant type checkers can understand and use that.
  2. Modify the type checker you're using somehow (mypy has an experimental "plugin" system, for example)
  3. Petition to modify PEP 484 to include your new, custom type (you can do this by opening an issue in the typing module repo).

这篇关于如何创建自己的“参数化"广告素材?输入Python(例如"Optional [T]")吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆