Python. Hint for variable

倾然丶 夕夏残阳落幕 提交于 2019-12-12 03:45:34

问题


I'm using PyCharm as editor. For example, I have next function:

def get_instance():
    # method without doc sctring in some module
    # returns instance of MyClass
    return some_var

And I have second file which calls get_instance():

var = get_instance()

How I can to define type of data for value? I want to use autocomplete for variable.

For example in php it will be like this:

/** @var MyClass $var */
$var = getInstance();

After this I will be see all methods and properties of $var. How to declare docstring for python variable? I know about :type and :rtype, but if I need declare type for specific variable? Can I declare a few types? What I should do?

Note: I can't do any changes with get_instance().


回答1:


I don't think you can do this via docstring, but there is a mechanism called annotation. You can append whatever expression you want to parameters following a colon : and to the function declaration itself using an arrow ->. For example:

def getInstance(param: str) -> MyClass
    return some_var

I have added an input parameter for purposes of illustration here. In this case str and MyClass are objects that represent the expected input and return types, respectively. They are never used in your code directly, just stashed away in an func_annotations attribute for end users that care about that sort of things (like editors).




回答2:


You can do it in the same way as description properties of class. Here example:

from example_module import MyClass

var = get_instance()
"""
:type var: MyClass
"""

Also you can use description without import like this:

var = get_instance()
"""
:type var: example_module.MyClass
"""

The second way is using PEP 484:

test = my()  # type: dict

Examples of autocomplete in Pycharm:



来源:https://stackoverflow.com/questions/40550805/python-hint-for-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!