Python生成器函数/对象命名约定

Dim*_*nek 5 python naming generator naming-conventions lightweight-processes

我在同一个类中实现了一些逻辑过程。一个类实例为每个过程获取一个生成器,并run()推进所述生成器。就我而言,生成器不会结束。

您如何在下面的代码中调用foo_functionfoo_object

class C(threading.Thread):
    def foo_function(self):
        """ generator *function*,
            logical process foo """
        while True:
            # some state checks
            if self.some_attr:
                # side-effects here
                pass
            yield

    def __init__(self):
        # generator *object*
        # i.e. process instance
        self.foo_object = self.foo_function()  # <- here

    def run(self):
        while True:
            next(self.foo_object)
            next(self.another_object)
            if xxx:
                next(self.yet_another_object)
Run Code Online (Sandbox Code Playgroud)

典型的方法是discoveryauthenticationwatchdog,等。

如何命名以合理方式定义生成器的函数和包含生成器对象的属性?

最后,只是踢一下,同一个名字会疯了,对吗?

class C:
    def foo(self):
        yield 1; yield 2
    def __init__(self):
        self.foo = self.foo()

c = C()            
type(C.foo) is function
type(c.foo) is generator
Run Code Online (Sandbox Code Playgroud)

Ray*_*nda 4

您可以使用您自己设计的某种约定,根据函数名称自动创建包含生成器的成员。例如,在我的约定中,所有生成器都将包含在名为: 的成员中<function_name>_gen

我将函数名称称为其职责:discoveryauthenticationwatchdog都是好名字。所以你只需要一种自动设置的方法:self.discovery_genself.authentication_genself.watchdog_gen

代码示例:

class C:

    def discovery(self):
        yield 1; yield 2

    # Register all the functions for wich you want to have a generator
    # object.
    REGISTERED_GEN_FUNCTIONS = [discovery]

    def __init__(self):

        for func in self.REGISTERED_GEN_FUNCTIONS:
            name = func.__name__
            # All generators objects will be called <function_name>_gen.
            setattr(self, "{0}_gen".format(name), getattr(self, name)())

a = C()
for i in a.discovery_gen:
    print(i)
Run Code Online (Sandbox Code Playgroud)

输出

>>> 1
>>> 2 
Run Code Online (Sandbox Code Playgroud)