如何告诉PyCharm期望参数是什么类型?
说到构造函数、赋值和方法调用,PyCharm这个开发工具在分析我的源代码方面做得相当不错,它能搞清楚每个变量应该是什么类型。我喜欢它能正确识别,因为这样可以给我提供很好的代码补全和参数信息,如果我试图访问一个不存在的属性,它还会给我警告。
但是,当涉及到参数时,它就无能为力了。代码补全的下拉菜单什么都显示不出来,因为它不知道这个参数会是什么类型。代码分析也无法查找警告。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth() # shows warning -- Person doesn't have a dig_filth method
class King:
def repress(self, peasant):
# PyCharm has no idea what type the "peasant" parameter should be
peasant.knock_over() # no warning even though knock_over doesn't exist
King().repress(peasant)
# Even if I call the method once with a Person instance, PyCharm doesn't
# consider that to mean that the "peasant" parameter should always be a Person
这也说得通。其他调用这个参数的地方可能会传入任何东西。但如果我的方法期望一个参数是某种类型,比如说 pygame.Surface
,我希望能以某种方式告诉PyCharm,这样它就可以在代码补全的下拉菜单中显示所有 Surface
的属性,并在我调用错误的方法时给我提示等等。
有没有办法让我给PyCharm一个提示,告诉它“嘿,这个参数应该是类型 X
”?(或者,按照动态语言的风格,“这个参数应该像 X
一样叫唤”?我对此也没问题。)
编辑:下面CrazyCoder的回答解决了这个问题。对于像我这样的新手,快速总结一下就是:
class King:
def repress(self, peasant):
"""
Exploit the workers by hanging on to outdated imperialist dogma which
perpetuates the economic and social differences in our society.
@type peasant: Person
@param peasant: Person to repress.
"""
peasant.knock_over() # Shows a warning. And there was much rejoicing.
相关的部分是文档字符串中的 @type peasant: Person
这一行。
如果你还去文件 > 设置 > Python集成工具,把“文档字符串格式”设置为“Epytext”,那么PyCharm的视图 > 快速文档查找将会漂亮地显示参数信息,而不是直接打印所有的@行。
5 个回答
PyCharm可以从@type的pydoc字符串中提取类型信息。 你可以在PyCharm的文档中找到相关信息,链接在这里和这里,还有Epydoc的文档。这个功能在PyCharm的“遗留”部分,可能缺少一些功能。
class King:
def repress(self, peasant):
"""
Exploit the workers by hanging on to outdated imperialist dogma which
perpetuates the economic and social differences in our society.
@type peasant: Person
@param peasant: Person to repress.
"""
peasant.knock_over() # Shows a warning. And there was much rejoicing.
相关的部分是文档字符串中的这一行:@type peasant: Person
。
我并不是想抢CrazyCoder或原提问者的积分,大家可以给他们积分。我只是觉得简单的答案应该放在“答案”位置。
如果你使用的是Python 3.0或更高版本,你可以在函数和参数上使用注解。PyCharm会把这些注解理解为参数或返回值应该是什么类型:
class King:
def repress(self, peasant: Person) -> bool:
peasant.knock_over() # Shows a warning. And there was much rejoicing.
return peasant.badly_hurt() # Lets say, its not known from here that this method will always return a bool
有时候,这对一些不公开的方法很有用,因为这些方法不需要文档字符串。额外的好处是,这些注解可以通过代码访问:
>>> King.repress.__annotations__
{'peasant': <class '__main__.Person'>, 'return': <class 'bool'>}
更新:根据PEP 484,这个提案已经被Python 3.5接受,现在也成为了官方的约定,用来通过注解来指定参数和返回值的类型。
是的,你可以使用一种特殊的文档格式来为方法和它们的参数说明类型,这样PyCharm就能识别这些类型。最近的PyCharm版本支持大多数常见的文档格式。
举个例子,PyCharm可以从@param 风格的注释中提取类型信息。
你还可以查看reStructuredText和文档字符串规范(PEP 257)。
另一个选择是使用Python 3的注解功能。
想了解更多细节和示例,请参考PyCharm的文档部分。