PyCharm 4.0.0 Web Help

In this section:

Basics

Python is dynamically typed. That's why one doesn't need to specify variable types explicitly. However, it is possible to use docstrings (reStructuredText, epytext) and py3 annotations to specify information about the expected types of the following values:

  • parameters passed to a function
  • return values
  • local variables
  • fields

PyCharm suggests code completion with these expected types.

Type syntax

Type syntax in Python docstrings is not defined by any standard. Thus, PyCharm suggests the following notation:

  • Foo # Class Foo visible in the current scope
  • x.y.Bar # Class Bar from x.y module
  • Foo | Bar # Foo or Bar
  • (Foo, Bar) # Tuple of Foo and Bar
  • list[Foo] # List of Foo elements
  • dict[Foo, Bar] # Dict from Foo to Bar
  • T # Generic type (T-Z are reserved for generics)
  • T <= Foo # Generic type with upper bound Foo
  • Foo[T] # Foo parameterized with T
  • (Foo, Bar) -> Baz # Function of Foo and Bar that returns Baz
  • list[dict[str, datetime]] # List of dicts from str to datetime (nested arguments)
  • :param "type_name" "param_name": "param_description" # Combining parameter type and documentation in a single line. See Sphinx documentation for details.)

Specifying types of parameters

Consider adding information about the expected parameter type. This information is specified using :type or @type docstrings:

py_type_hinting_param1

When Python 3 is specified as the project interpreter, you can also use annotations to specify the expected parameter type:

py_type_hinting_param2

Specifying return types

Use docstrings :rtype or @rtype to specify the expected return type:

py_type_hinting_return2

  • :rtype: collections.Iterable[int] # return type: 'items' is of type generator or collections.Iterable, 'a' is of type int, see the following code:
    def my_iter():
        for i in range(10):
            yield i
    items = my_iter()
    for a in items:
        print a
                
  • :rtype: list[int] for my_iter # return type: 'a' is of type int, see the following code:
    def my_iter():
        for i in range(10):
            yield i
    for a in my_iter():
        print a
                

When Python 3 is specified as the project interpreter, you can use annotations to specify the expected return type:

py_type_hinting_return1

Specifying types of local variables

Consider adding information about the expected type of a local variable using :type or @type docstrings:

py_type_hinting_local_var1

It is also possible to use isinstance to define the expected local variable type:

py_type_hinting_local_var2

Specifying types of fields

Finally, you can use type hinting to specify the expected type of fields:

py_type_hinting_field

Annotating lists and dictionaries

:type: dict of [str, C]
:type: list of [str]
    

See Also

Procedures:

External Links:

Web Resources: