如何为 greenlet 命名

How can I assign a name to a greenlet

我希望将自定义 name/identifier 分配给 gevent greenlet。 Gevent 已经分配了一个唯一的名称:

def name(self):
    """
    The greenlet name. By default, a unique name is constructed using
    the :attr:`minimal_ident`. You can assign a string to this
    value to change it. It is shown in the `repr` of this object.

    .. versionadded:: 1.3a2
    """

但是,我不确定如何将此值更改为用户输入的名称。有可能这样做吗?

我试图做这样的事情,结果出现属性错误:

       def begin(self):
          self.thread = gevent.spawn(self.print_message)
          self.thread.minimal_ident = "t1"
          print(self.thread.name) 

AttributeError: attribute 'minimal_ident' of 
'gevent._greenlet.Greenlet' objects is not writable

首先实例化class,然后覆盖该方法;

my_obj = Class() #Instantiate the class
my_obj.name = 'this is the string'

这将用您自己的字符串替换构造的名称。

gevent.Greenlet.name 不是常见的 property,而是 gevent.util.readproperty obj,即 a special non-data descriptor 的工作方式类似于 @property,并且对于非数据描述符:

... In contrast, non-data descriptors can be overridden by instances.

您可以简单地覆盖它:

>>> gr = gevent.spawn(gevent.sleep, (1,))
>>> gr.name = "a_cool_name"
>>> print(gr)
<Greenlet "a_cool_name" at 0x1082a47b8: sleep((1,))>

阅读有关 gevent 源代码的更多信息和 the descriptor doc