简体   繁体   中英

Type hinting in Eclipse with PyDev

I'm studying Python, after a lot of PHP experience, and it would be handy to have type-hinting in Python. Looks like Eclipse with PyDev doesn't support this. Any suggestions?

For example, I want my IDE to show function docstrings and types , when I use it, like:

def f(x: int) -> int:
    r"""Adds 3 to x"""
    return x + 3

f(# and now IDE shows everything about types 

Python is a dynamically-typed language, where variable types don't need to be declared. You can add information about the expected types intended to be passed to the function in docstrings though, eg

def f(x):
    """
    @x: int
    Adds 3 to x
    returns an int
    """
    return x + 3

But in this case, the function is so simple it doesn't need any type info in my opinion and just documenting what it does is often preferred in python over documenting strict types.

pydev does support docstring (but not types) completion and catches many errors, so long as you're opening the python files as part of a project and not opening them separately by drag-dropping them into Eclipse.

You need to add the folders containing python files by right clicking on the project root, selecting the Properties menu item and selecting PyDev - PYTHONPATH on the list on the left, and clicking Add source folder for all the folders with python files. Note that pydev can usually find modules in any subdirectories if there's a __init__.py in them, so you often only need to add the root python source folder.

After that, you access the tooltips by typing ctrl+space before typing the ( , and auto-fill out suggested function arguments by typing ctrl+space after typing ( .

See also the pydev manual at http://pydev.org/manual_101_root.html

Present Python 2/3

For local scope variables and function parameters PyDev has this:

assert isinstance(obj, MyClass)
obj. # here hint will work

Though I guess it's a not documented feature. Here's PyDev's official page for type hints and couple of excerpts which illustrate Sphinx syntax.

class Example:

  def param(self, a):
    ''':type a: MyClass'''

  def var(self, iterable):
    for a in iterable: #: :type a: AnotherClass
        pass

Unfortunately, neither works for class members.

Since, PyDev 4 there's also something that can resemble PEP-484 (see below).

class LatestExample:

  def listcase(self, param):
    ''':type param: list[str]'''

  def dictcase(self, param):
    ':type param: dict[str, MyClass]'

Future Python 3

Take a look at answer by @slushy. No doubt this is the future. But for the time being PyDev supports neither function annotations, PEP-3107 , nor new PEP-484 stuff @slushy demonstrates. PEP-484 is coming in Python 3.5 in some limited form, and in 3.6 in final. Here's BDFL's PyCon 2015 presentation for type hints and PEP-484.

As of August 2014 there is a proposal by Guido Van Rossum to use mypy syntax annotate type in function definitions, stating that the new syntax is actually valid Python 3. An example from his proposal (not yet a PEP as of September 2014)

from typing import List, Dict

def word_count(input: List[str]) -> Dict[str, int]:
    result = {}  #type: Dict[str, int]
    for line in input:
        for word in line.split():
            result[word] = result.get(word, 0) + 1
    return result

I'm not aware of any ways to do type-hinting in Python.

The standard Pythonic practice is this:

>>> def adds_three(number):
...     '''Returns number + 3'''
...     return number + 3
...     

Note I've done the following:

  • The function name is clear for its behaviour
  • The argument name is clear as to what it should be
  • The docstring details what the function does
  • Python is a dynamically-typed language. Why restrict the user to put in integer? Floating points also support the operator + . Let them use it.

One good thing about dynamic typing is that all methods are inheritly overloaded. Of course, you can always do type-checking in the function to prevent fatal errors.

reStructuredText , epytext and python3 annotations can define expected types in Python code, and are supported by various integrated development environments such as pycharm . This is particularly handy for defining class names, as it allows autocomplete of members.

A simple example in epytext:

def x_intercept(m, b):
    """
    Return the x intercept of the line M{y=m*x+b}.  The X{x intercept}
    of a line is the point at which it crosses the x axis (M{y=0}).

    @type  m: float
    @param m: The slope of the line.
    @type  b: number
    @param b: The y intercept of the line.  The X{y intercept} of a
              line is the point at which it crosses the y axis (M{x=0}).
    @rtype:   number
    @return:  the x intercept of the line M{y=m*x+b}.
    """
    return -b/m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM