在 python 函数中输入提示特定整数值

问题描述 投票:0回答:2

我正在学习输入提示我的函数和文件的技能。

但是我遇到了一个奇怪的情况。

我有一个函数,按照约定只能接受 3 个选定的整数作为参数:0、1 和 2。 所以我制作了以下相关代码行:

def func(number: 0 | 1 | 2):
    print(number)

input_number = 0
func(input_number)

但是当我输入

mypy test.py
时,我收到以下错误:

test.py:1: error: Invalid type: try using Literal[0] instead?  [valid-type]
test.py:1: error: Invalid type: try using Literal[1] instead?  [valid-type]
test.py:1: error: Invalid type: try using Literal[2] instead?  [valid-type]

所以我决定用字面量来写:

from typing import Literal

def func(number: Literal[0, 1, 2]):
    print(number)

input_number = 0

func(input_number)

但现在我明白了:

test.py:3: error: Argument 1 to "func" has incompatible type "int"; expected "Literal[0, 1, 2]""  [arg-type]

我最初的猜测是

Literal
意味着只包含
str
值,所以我改变了
input_number
:

input_number = '0'

但是稍加改动就会出现同样的错误:

test.py:3: error: Argument 1 to "func" has incompatible type "str"; expected "Literal[0, 1, 2]"  [arg-type]

总是尝试研究其他人和图书馆的工作以及他们如何实施不同的技术,但我从未见过这样的事情

并且我知道如果我的代码可以正常工作,我可以忽略

type hints
中的错误。但这对我来说是一个奇怪的错误,我无法逃避痒

python type-hinting
2个回答
0
投票

mypy 是一个静态分析器。如果您声明一个函数接受文字参数,则它将只接受文字值,并且永远不会接受任何变量。原因是该值是运行时的东西,而 mypy 是一个 compile 时工具。

所以你只剩下2个选择:

  • 声明一个文字参数并记录该函数确实需要一个文字值 - 相当不常见的方法

  • 声明一个int参数并在运行时控制该参数具有预期值:

      def func(number: int):
          if not 0<=number<=2:
              raise ValueError('func only accepts 0,1 or 2 value')
          print(number)
    

0
投票

如果仅需要输入文档,您可以使用枚举:

from enum import IntEnum

class AcceptedNumber(IntEnum):
    ONE = 1
    TWO = 2
    THREE = 3

def func(number: AcceptedNumber):
    print(number)

input_number = 0

func(input_number)

这样,您也可以避免幻数

© www.soinside.com 2019 - 2024. All rights reserved.