python自己开发软件接入广告_如何创建自己的“参数化”广告素材?输入Python(例如“ Optional [T]”)吗?...

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]]

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.

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.

解决方案

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:

Construct some kind of custom class/metaclass thing that PEP 484-compliant type checkers can understand and use that.

Modify the type checker you're using somehow (mypy has an experimental "plugin" system, for example)

Petition to modify PEP 484 to include your new, custom type (you can do this by opening an issue in the typing module repo).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值