Python 3 类型检查不适用于使用类型模块? [英] Python 3 type check not works with use typing module?

查看:54
本文介绍了Python 3 类型检查不适用于使用类型模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么类型检查在 Python 3 中不起作用?

我已经完成了以下带有类型检查或提示的代码:

导入输入定义你好(消息:str):打印(类型(消息))打印(消息)你好你好!')你好(1)你好(1.1)

它产生有效的输出(但在 int 或 float 上没有错误).

你好!<类'int'>1<类'浮动'>1.1

为什么会这样?也许我不明白打字模块和 Python 提示.

解决方案

Python 的类型提示仅供参考.类型检查或参数类型的自动强制不是语言的一部分.请参阅PEP 3107:

<块引用>

函数注解只不过是在编译时将任意 Python 表达式与函数的各个部分相关联的一种方式.

类型提示可以被附加模块用来检查参数和返回值的类型,甚至将参数强制转换为预期的类型.例如,这里 是一个模块,它将检查参数类型并在发现不匹配时进行投诉.>

但这不是 Python 本身的工作方式,所以不要依赖它,也不要想方设法将它带入您的代码中.在 Python 风格中,你的函数应该尽可能灵活地编写它们可以使用的参数类型(谷歌鸭子类型").如果他们得到一些他们无法处理的东西......好吧,这就是例外.

更新:打字 提供类型提示支持的模块从 Python 3.5 开始被添加到标准库中(在临时基础上").它提供了一些有用的类型名称,包括 AnyCallableUnion,以及一个辅助函数 NewType.类型提示仍然非常非常可选.

Why does type checking not work in Python 3?

I have done the following code with type checks or hints:

import typing

def hello(message: str):
    print(type(message))
    print(message)

hello('Hello!')
hello(1)
hello(1.1)

It produces valid output (but no errors on int or float).

<class 'str'>
Hello!
<class 'int'>
1
<class 'float'>
1.1

Why does it works this way? Maybe I don't understand the typing module and Python hints.

解决方案

Python's type hints are informational only. Type checking or automatic coercion of argument types are not part of the language. See PEP 3107:

Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.

The type hints could be used by an add-on module to check the types of arguments and returned values, or even to coerce arguments to the expected type. For example, here is a module that will check argument types and complain if it finds a mismatch.

But this is not how Python itself works, so don't rely on it and don't look for ways to bring it into your code. In Python style, your functions should be written to be as flexible as possible about the argument types they can work with (google "duck typing"). If they get something they can't handle... well, that's what exceptions are for.

Update: The typing module, which provides support for type hints, was added to the standard library ("on a provisional basis") as of Python 3.5. It provides some useful type names including Any, Callable and Union, and a helper function NewType. Type hints remain very, very optional.

这篇关于Python 3 类型检查不适用于使用类型模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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