首页 文章

我如何告诉PyCharm参数的类型是什么?

提问于
浏览
164

在构造函数,赋值和方法调用方面,PyCharm IDE非常擅长分析我的源代码并确定每个变量应该是什么类型 . 我喜欢它,因为它给了我很好的代码完成和参数信息,如果我尝试访问不存在的属性,它会给我警告 .

但是当谈到参数时,它什么都不知道 . 代码完成下拉列表无法显示任何内容,因为它们不知道参数的类型 . 代码分析无法查找警告 .

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一个提示,并说“psst,这个参数应该是X型”? (或者,或许,在动态语言的精神中,“这个参数应该像X一样嘎嘎”?我会好的 . )


EDIT: 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.

相关部分是docstring的 @type peasant: Person 行 .

如果您还转到文件>设置> Python集成工具并将“文档字符串格式”设置为“Epytext”,那么PyCharm的视图>快速文档查找将完全打印参数信息,而不是仅按原样打印所有@ -lines .

5 回答

  • 80

    PyCharm extracts types from a @type pydoc string. 参见PyCharm docs herehere,以及Epydoc docs . 它是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.
    

    相关部分是docstring的 @type peasant: Person 行 .

    我的目的不是要从CrazyCoder或原始提问者那里偷点,一定要给他们分数 . 我只是认为简单的答案应该在“回答”位置 .

  • 3

    你也可以断言一个类型,Pycharm会推断它:

    def my_function(an_int):
        assert isinstance(an_int, int)
        # Pycharm now knows that an_int is of type int
        pass
    
  • 45

    是的,您可以为方法及其参数使用特殊的文档格式,以便PyCharm可以知道类型 . 最近的PyCharm版本supports most common doc formats .

    例如,PyCharm从@param style comments中提取类型 .

    另见reStructuredTextdocstring conventions(PEP 257) .

    另一个选项是Python 3注释 .

    refer to the PyCharm documentation section了解更多详情和样品 .

  • 1

    如果您使用的是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
    

    有时这对非公共方法很有用,不需要docstring . 作为额外的好处,可以通过代码访问这些注释:

    >>> King.repress.__annotations__
    {'peasant': <class '__main__.Person'>, 'return': <class 'bool'>}
    

    Update :从PEP 484开始,已经被Python 3.5接受,它也是使用注释指定参数和返回类型的官方约定 .

  • 1

    我正在使用PyCharm Professional 2016.1编写py2.6-2.7代码,我发现使用reStructuredText我可以用更简洁的方式表达类型:

    class Replicant(object):
        pass
    
    
    class Hunter(object):
        def retire(self, replicant):
            """ Retire the rogue or non-functional replicant.
            :param Replicant replicant: the replicant to retire.
            """
            replicant.knock_over()  # Shows a warning.
    

    见:https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html#legacy

相关问题