Error: types.coroutine() expects a callable

2019-07-28 09:57发布

I have the following class:

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() expects a callable

Can you tell me what the problem is?

=> edit Code calling this function

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

1条回答
叛逆
2楼-- · 2019-07-28 10:14

The problem is that classmethod does... interesting things. Once the class definition has finished you have a nice callable method on the class, but during the definition you have a classmethod object, which isn't callable:

>>> 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

The simplest fix is to re-order the decorators, so that rather than trying to turn a classmethod into a coroutine:

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

you are trying to turn a coroutine into a classmethod:

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

Note that the decorators are applied "inside out", see e.g. Decorator execution order

查看更多
登录 后发表回答