我正在学习 Python,在拥有大量 PHP 经验之后,在 Python 中使用 type-hinting 会很方便。看起来 Eclipse 和 PyDev 不支持这个。有什么建议吗?
例如,我希望我的 IDE 在使用时显示函数 docstrings 和 types,例如:
def f(x: int) -> int:
r"""Adds 3 to x"""
return x + 3
f(# and now IDE shows everything about types
对于局部作用域变量和函数参数 PyDev 有这样的:
assert isinstance(obj, MyClass)
obj. # here hint will work
虽然我猜这是一个没有记录的功能。这是 PyDev 的关于类型提示的官方页面以及一些说明 Sphinx 语法的摘录。
class Example:
def param(self, a):
''':type a: MyClass'''
def var(self, iterable):
for a in iterable: #: :type a: AnotherClass
pass
不幸的是,这两种方法都不适用于班级成员。
从 PyDev 4 开始,还有一些类似于 PEP-484 的东西(见下文)。
class LatestExample:
def listcase(self, param):
''':type param: list[str]'''
def dictcase(self, param):
':type param: dict[str, MyClass]'
看看@slushy 的回答。毫无疑问,这就是未来。但目前 PyDev 既不支持函数注释PEP-3107,也不支持@slushy 演示的新的PEP-484。 PEP-484 以某种有限的形式出现在 Python 3.5 中,并最终出现在 3.6 中。这是 BDFL 的 PyCon 2015 演示文稿,用于类型提示和 PEP-484。
Python 是一种动态类型语言,不需要声明变量类型。不过,您可以在文档字符串中添加有关要传递给函数的“预期”类型的信息,例如
def f(x):
"""
@x: int
Adds 3 to x
returns an int
"""
return x + 3
但在这种情况下,该函数非常简单,在我看来不需要任何类型信息,并且在 python 中,仅记录它的作用通常比记录严格类型更受欢迎。
pydev 确实支持文档字符串(但不支持类型)完成并捕获许多错误,只要您将 python 文件作为项目的一部分打开,而不是通过将它们拖放到 Eclipse 中来单独打开它们。
您需要添加包含 python 文件的文件夹,方法是右键单击项目根目录,选择
Properties
菜单项,然后选择左侧列表中的
PyDev - PYTHONPATH
,然后单击 Add source folder
添加所有包含 python 文件的文件夹。请注意,如果模块中有 __init__.py
,pydev 通常可以在任何子目录中找到模块,因此您通常只需要添加 root python 源文件夹即可。之后,您可以通过键入
ctrl+space
before键入
(
访问工具提示,并通过键入 ctrl+space
after键入
(
自动填写建议的函数参数。 另请参阅 pydev 手册:http://pydev.org/manual_101_root.html
,在函数定义中使用 mypy 语法注释类型,指出新语法实际上是有效的 Python 3。他的提案中的一个示例(截至目前还不是 PEP) 2014 年 9 月)
from typing import List, Dict
def word_count(input: List[str]) -> Dict[str, int]:
result = {} #type: Dict[str, int]
for line in input:
for word in line.split():
result[word] = result.get(word, 0) + 1
return result
标准的 Pythonic 实践是这样的:
>>> def adds_three(number):
... '''Returns number + 3'''
... return number + 3
...
注意我已完成以下操作:
函数名称清楚地表明其行为
+
、epytext和python3注解可以定义Python代码中期望的类型,并且受到pycharm等各种集成开发环境的支持。 这对于定义类名特别方便,因为它允许自动完成成员。 epytext 中的一个简单示例:
def x_intercept(m, b):
"""
Return the x intercept of the line M{y=m*x+b}. The X{x intercept}
of a line is the point at which it crosses the x axis (M{y=0}).
@type m: float
@param m: The slope of the line.
@type b: number
@param b: The y intercept of the line. The X{y intercept} of a
line is the point at which it crosses the y axis (M{x=0}).
@rtype: number
@return: the x intercept of the line M{y=m*x+b}.
"""
return -b/m