Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hinting class not yet imported

I've got the following code:

def render(self, notification):
    """
    @type notification: Notification
    """
    return NotificationRepresentation(notification).to_dict()
    # some irrelevant code

notification is a Notification class instance. Notification class is not imported here, and PyCharm can't use that type hinting (inferred type: unknown).

I've tried using full class name, it didn't work. The obvious way is to import the class, but it never used, so it would be a redundant import (and PyCharm will remove it while optimizing imports before commit). Less obvious way is to do some weird thing like Celery.task do:

STATICA_HACK = True
globals()['kcah_acitats'[::-1].upper()] = False
if STATICA_HACK:
    # This is never executed, but tricks static analyzers (PyDev, PyCharm,
    # pylint, etc.) into knowing the types of these symbols, and what
    # they contain.
    from celery.canvas import group, chord, subtask
    from .base import BaseTask, Task, PeriodicTask, task, periodic_task
    from .sets import TaskSet

Is there any clean way to do this?

like image 269
J0HN Avatar asked Nov 19 '13 06:11

J0HN


1 Answers

Provide the full path to the class you want to reference.

def render(self, notification, my_subtask):
    """
    @type notification: full.path.to.Notification
    @type my_subtask: celery.canvas.subtask
    """
    return NotificationRepresentation(notification).to_dict()
    # some irrelevant code

It might be a problem with your older installation, because providing the full path works for me in PyCharm 3.0. Try upgrading ;)

like image 160
Patch Rick Walsh Avatar answered Oct 17 '22 00:10

Patch Rick Walsh