元组键入至少x个类型

时间:2018-01-21 18:36:12

标签: python python-3.x types tuples

根据Python Typing的文档,这些是处理元组的文件......

  • Tuple[()] - 空元组
  • Tuple[int, int] - 两个int对象的元组
  • Tuple[int, ...] - 任意数量的int对象的元组

我想创建一个类型,其中Tuple至少有int个。{/ strong> 我的目标介于最后两种类型之间(Tuple[int, int]Tuple[int, ...])。

如果元组有......

  • 8个整数?好
  • 9整?好
  • 32英寸?好
  • 4个整数?坏
  • 1 int?坏

在PyCharm不会发出警告的情况下,这是否可能?这是我在下面尝试的。然而,PyCharm将错误地#34;在assert声明

上给我警告
# Type Alias 
Byte = Tuple[int, int, int, int, int, int, int, int]           # 8 bits
Nibble = Tuple[int, int, int, int]                             # 4 bits

# BytePlus Type is not correct. The following code does not work
BytePlus = Tuple[int, int, int, int, int, int, int, int, ...]  # 8+ bits


def adder(byte1: Union[Byte, BytePlus], byte2: Byte) -> Byte:
    pass

# Incorrect warnings for parameters. 
# What I see...
#    - parameter 1 (Byte | BytePlus) has no warning, but it should. nibble = 4 bits
#    - parameter 2 (Byte) has a warning, good, but it will have a warning for 9 bits
assert adder(nibble(4), nibble(10)) == byte(14)

以下是nibble()byte()的代码,如果您需要......

def byte(number) -> Byte:
    return (
        (number & 128) // 128,
        (number & 64) // 64,
        (number & 32) // 32,
        (number & 16) // 16,
        (number & 8) // 8,
        (number & 4) // 4,
        (number & 2) // 2,
        (number & 1) // 1
    )


def nibble(number) -> Nibble:
    return (
        (number & 8) // 8,
        (number & 4) // 4,
        (number & 2) // 2,
        (number & 1) // 1
    )

0 个答案:

没有答案