Home > OS >  Type hints in PyCharm for Python 2.7 (named tuple)
Type hints in PyCharm for Python 2.7 (named tuple)

Time:04-16

Unfortunately autocompletion on args does not work inside the method foo()

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from collections import namedtuple

CreateVhostDoArgs = namedtuple('CreateVhostDoArgs',
                               ['project_directory', 'branch', 'vhost_dir'])


def foo(args):
    # type (CreateVhostDoArgs) -> None
    print(args.project_directory)



if __name__ == '__main__':
    foo(CreateVhostDoArgs('pd', 'branch', 'dir'))

How can I change my type-hint, so that PyCharm provides me autocomplete on args.proje...?

CodePudding user response:

Try:

def foo(args):
   """
   :type args: CreateVhostDoArgs
   """ 

In the settings there are different docstring formats which might be of use to you. Settings | Tools | Python Integrated Tools The default which I tested with is reStructredText. The other ones might behave a little differently (or not at all)

In this SO post I try to expand a-lot on type hinting in PyCharm if you want some more details.

I did this a-lot a number of years ago when python first introduced type hinting and pycharm quickly rolled out an update supporting it, but it did not support everything that the PEP outlines, and I think I only found reStructredText to work, but things might have changed since then. When I was doing it back then I remember it being really annoying with maintenance of class names changing and that not getting propagated to the docstrings properly. If that type isn't actually used in the file (not imported) it just won't give an error or warning and I guess it just thinks you are a dumb user writing stuff in there incorrectly. Then you need to do an import just for something in the comments, which it doesn't seem like PyCharm is complaining these days about that, but if you have other linters they might. There are probably other pitfalls to watch out for too, so tread cautiously.

It definitely works, but I don't recommend it to anyone in python 3.5 (when python introduced type hinting) for reasons detailed in the other post.

I did test locally specifically with namedtuple and it worked.

  • Related