类型提示类尚未导入

时间:2013-11-19 06:58:44

标签: python pycharm type-hinting

我有以下代码:

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

notificationNotification类实例。此处未导入Notification类,PyCharm无法使用该类型提示(inferred type: unknown)。

我尝试过使用全班名,但是没用。显而易见的方法是导入类,但它从未使用过,因此它将是一个冗余导入(并且PyCharm将在提交之前优化导入时删除它)。不太明显的方法是做一些像Celery.task那样奇怪的事情:

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

有没有干净的方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

提供要引用的类的完整路径。

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

旧安装可能有问题,因为在PyCharm 3.0中为我提供了完整路径。尝试升级;)