0

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().

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
  • have you looked at [Hints](https://docs.python.org/3/library/typing.html)? – Olian04 Nov 11 '16 at 15:11
  • Could you clarify where exactly you need or want to use docstrings? – Right leg Nov 11 '16 at 15:11
  • @Rightleg in any place of code. Example: `get_docker()` return `Docker` instance(I know it). But function without docstring and I can't change it. So, I calls `var = get_docker()`.And I want to define type of `var`(that it is Docker instance). – Danila Ganchar Nov 12 '16 at 10:21
  • @Olian04 it is works only with python 3. Right? One more thing: I can't change function. I need just define type of variable. See my comment above. – Danila Ganchar Nov 12 '16 at 10:24

2 Answers2

3

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).

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Thanks for the answer. But how I know it's works only with python 3. Is it true? The similar way - using `:type` in docsting for each param. But sometimes convenient to specify the instance of variable(especially if you can't change docstring of function which was calls). – Danila Ganchar Nov 12 '16 at 10:13
0

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:

enter image description here

enter image description here

enter image description here

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75