2

How can I tell pycharm that the return type of form.save() is, in this case, a CategoryQuestion object?

def category_ask(request):
    if request.method == 'POST':
        form = CategoryQuestion_form(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.who = request.user
            question.dat<tab>
Bryce
  • 8,313
  • 6
  • 55
  • 73

4 Answers4

5

Use "assert isinstance(x, Type)" to fake pycharm into knowing the proper type for the local variable. Pycharm then knows the proper type, and tab completion will work:

def category_ask(request):
    if request.method == 'POST':
        form = CategoryQuestion_form(request.POST)
        if form.is_valid():
            question                = form.save(commit=False)
            assert isinstance(question, models.CategoryQuestion)
            question.who            = request.user
            question.date_created<tab>

As of pycharm 1.2, unfortunately you can't just use a bare unchecked "isinstance()", the assert is required.

Bryce
  • 8,313
  • 6
  • 55
  • 73
4

PyCharm 3 (not sure about earlier versions) supports type-hinting of local variables (as well as paramters) via :type or @type docstrings.

 def category_ask(request):
    if request.method == 'POST':
        form = CategoryQuestion_form(request.POST)
        if form.is_valid():
            # :type models.CategoryQuestion
            question = form.save(commit=False)
            question.who = request.user
            question.dat<tab>

Check out the official docs: http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html#d68026e604

Stefan
  • 736
  • 4
  • 18
  • Did not work for me Pycharm 3.4. It worked for the integer type as in the docs, but not for a model. – Bryce Sep 02 '14 at 20:38
3

In Pycharm 3, @type hinting for local variables is picky, but works. It must appear on the line after the assignment, and appears to required the triple quote syntax:

        if form.is_valid():
            question = form.save()
            """@type : CategoryQuestion"""
            question.dat<tab>

Check out the official docs: http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html#d68026e604

Bryce
  • 8,313
  • 6
  • 55
  • 73
2

For those using python3.6 and higher:
Type Hinting is now a part of python and works well with pycharm.
You can add a : after the name of a variable to hint its type such as some_varibale: str. The same rule is applied for arguments.
So, in this case, the variable is hinted to be CategoryQuestion this way:

question: CategoryQuestion = form.save(commit=False)

To know how to type hint a queryset such as filter see here
You can also use django_hint which has type hint classes specifically for Django.

Ramtin
  • 3,058
  • 1
  • 22
  • 24