问题
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