【问题标题】:Error: types.coroutine() expects a callable错误:types.coroutine() 需要一个可调用的
【发布时间】:2016-10-26 00:55:04
【问题描述】:

我有以下课程:

from tornado import gen

class VertexSync(Vertex):
    @wait_till_complete
    @gen.coroutine
    @classmethod
    def find_by_value(cls, *args, **kwargs):
        stream = yield super().find_by_value(*args, **kwargs)
        aggr = []
        while True:
            resp = yield stream.read()
            if resp is None:
                break
            aggr = aggr + resp
        return aggr

TypeError: types.coroutine() 需要一个可调用对象

你能告诉我问题是什么吗?

=> 编辑 调用该函数的代码

print(DemoVertex.find_by_value('longitude', 55.0))

【问题讨论】:

  • @classmethod 不返回可调用对象。切换装饰器,以便首先调用 gen.coroutine
  • 请包含调用此函数的代码。
  • @jonrsharpe @classmethod 返回什么以及如何使它成为一个协程?
  • @freeza 它返回<classmethod object at 0x...>TypeError: 'classmethod' object is not callable。您需要重新订购您的装饰器。
  • @advance512 请注意,在这种情况下并不重要,因为错误是在类定义时抛出的。

标签: python tornado


【解决方案1】:

问题是classmethod 确实...有趣的事情。一旦类定义完成,你就有了一个很好的类可调用方法,但是在定义过程中你有一个classmethod object,这是不可调用的:

>>> a = classmethod(lambda self: None)
>>> a
<classmethod object at 0x10b46b390>
>>> callable(a)
False
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'classmethod' object is not callable

最简单的解决方法是重新排序装饰器,而不是试图将类方法变成协程:

@gen.coroutine
@classmethod
def thing(...):
    ...

您正在尝试将协程转换为类方法:

@classmethod
@gen.coroutine
def thing(...):
    ...

请注意,装饰器的应用“由内而外”,参见例如Decorator execution order

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2020-09-10
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多