区分用户函数返回和包装类返回

时间:2012-03-02 20:20:43

标签: python user-controls standards

我无法开发一个标准,用于从在类中运行和执行的用户函数返回数据,该类将函数作为单独的线程运行。

目标是在用户请求时从函数传递返回参数。

但是,如果用户从我的班级请求数据时函数没有完成运行怎么办?或者,如果函数失败并因此没有数据(但它的失败对程序来说并不重要,意味着引发异常过多)

我曾想过只返回None但是如果用户函数返回None并且有意义(即函数成功完成)怎么办?我的下一个想法是在列表中返回函数输出,如果没有数据准备好或可用,则返回None。这意味着用户必须检查数据是否被返回(检查无或列表),我发现这些数据有点不合适。

我很好奇是否已经有类似这样的标准,或者有人提出更清洁的建议。

示例:

用户来电

def foo():
    #...do lots of stuff that takes long time

    # return whether stuff worked or not (None if worked False if not)
    return success 

takes_forever = detach(foo)

# ... do other things

# get data from detached function which has hopefully completed
are_you_done = takes_forever.give_me_data()

我的课程:

class detach:
    def __init__(self, func):
        self.detached_func = execute_as_thread(func)

    def give_me_data(self) 
        if self.detached_func.is_done():        # function completed and didnt die
            return [self.detached_func.output]
        else:                                   # something went wrong or function is still running
            return None

2 个答案:

答案 0 :(得分:1)

最好是提出异常,如果由于某种原因你想避免返回一个特殊的对象,例如定义类NoResultsType并返回此类型的对象,或者可能只是类

class NoResultsType(object): pass

NoResults = NoResultsType()

def give_me_data(self) 
    if self.detached_func.is_done():        # function completed and didnt die
        return [self.detached_func.output]
    else:                                   # something went wrong or function is still running
        return NoResults

然后你可以定义多个这样的类型,例如NoResults,FunctionFailed等用户可以检查它们,例如

ret = foo.give_me_data()
if ret in [NoResultsYet, FunctionFailed]:
   # do something

或者你可以返回一个Result对象,它可以保留原始结果,状态等

class Result(object):
    def __init__(self):
         self.finished = False
         self.success = False
         self.error = ""
         self.result = None

res = foo.give_me_data()
if res.success:
    print res.result

答案 1 :(得分:0)

您可以在分离类上使用两种方法:

<强> is_finished() 告诉您函数调用是否仍在执行。

<强> GET_DATA() 将获得detached_func的返回值。如果函数尚未完成,它将一直阻塞,直到函数完成。

我不知道任何python标准,但你可以看看Java的Future类,它包装了异步执行的任务的结果。 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html