在'self'返回之前调用setattr

时间:2017-02-24 15:50:31

标签: python setattr luigi

我怀疑这对我来说是一种klugefest,但我正在使用Luigi和Sciluigi模块,这些模块设置了许多关键参数,在init之前返回'self'。如果我在自我返回后尝试对这些参数进行处理,那么Luigi.Parameter对象会以这样的方式掩盖它们,以至于我无法做我需要做的事情。

luigi和sciluigi类(使用它们)不包含__init__。如果我尝试插入__init__或调用super(ChildClass, self).__init__(*args, **kwargs) ...我会收到奇怪的错误'意外参数'错误。

所以Sciluigi课程看起来像这样......

class MyTask(sciluigi.task):
    param1 = sciluigi.Parameter(default='Yes') #String only
    param2 = sciluigi.Parameter(default='No')  #String only

    def out_target(self):
        return sciluigi.TargetInfo(self, self.out)

    def run(self):
        with self.out_target().open('w') as foofile:
            foofile.write('foo\n')

所以...我希望我可以通过setattr PRIOR动态设置一些参数,实际返回'self'。但是setattr需要这个对象。

我希望我能做点像......

setattr(inspect.stack()[?][?], 'DynamicVar', sciluigi.Parameter(default='Yes') )

编辑:@Charles Duffy

好吧,我不确定哪些信息最有帮助。

第一个问题是;我无法添加init。实际代码如下,添加了__init__方法。如果我尝试运行它,我已经包含了结果错误。它是同样的错误,如果我运行超级调用__init__

class FileConverter(sciluigi.Task):
    """
    """
    in_target   = None # Mandatory
    out = sciluigi.Parameter() # <file>
    exepath = sciluigi.Parameter(default = "") 

    def __init__(self):
        self.var = 'anything'

    def out_target(self):
        log.debug("In 'FileConverter.out_target'... ")
        return sciluigi.TargetInfo(self, self.out)

    def run(self):
        result = None
        command = ''.join([
                           self.exepath, _slash, "FileConverter ",
                           " -in ", self.in_target().path,
                           " -out ", self.out_target().path, 
                           " -out_type ", self.file_type
                           ])
        log.info("RUNNING COMMAND: " + command)
        result = self.ex(command)
        log.info("result: " + result[1])

错误

2017-02-24 17:01:48 |  WARNING | Will not run MyWorkflow(instance_name=sciluigi_workflow) or any dependencies due to error in deps() method:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/luigi/worker.py", line 697, in _add
    deps = task.deps()
  File "/Library/Python/2.7/site-packages/luigi/task.py", line 572, in deps
    return flatten(self._requires())
  File "/Library/Python/2.7/site-packages/luigi/task.py", line 544, in _requires
    return flatten(self.requires())  # base impl
  File "/Library/Python/2.7/site-packages/sciluigi/workflow.py", line 105, in requires
    workflow_output = self.workflow()
  File "/Users/mikes/Documents/Eclipseworkspace/Bioproximity/OpenMS-Python-Luigi/site-packages/Bioproximity/sciluigi_tasks/PipelineTest1.py", line 33, in workflow
    exepath = "/Applications/OpenMS-2.1.0/TOPP"
  File "/Library/Python/2.7/site-packages/sciluigi/workflow.py", line 145, in new_task
    newtask = sciluigi.new_task(instance_name, cls, self, **kwargs)
  File "/Library/Python/2.7/site-packages/sciluigi/task.py", line 37, in new_task
    newtask = cls.from_str_params(kwargs)
  File "/Library/Python/2.7/site-packages/luigi/task.py", line 412, in from_str_params
    return cls(**kwargs)
  File "/Library/Python/2.7/site-packages/luigi/task_register.py", line 99, in __call__
    h[k] = instantiate()
  File "/Library/Python/2.7/site-packages/luigi/task_register.py", line 80, in instantiate
    return super(Register, cls).__call__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'instance_name'

第二个问题是:

如果我等待自己回来,我再也无法区分(例如使用上面的代码)......

in_target   = None # Mandatory
out = sciluigi.Parameter() # <file>

如果我执行type(out),则键入报告参数只是一个字符串(而不是sciluigi.Parameter对象),所以如果我尝试使用`instsinstance(out,sciluigi.Parameter)...返回False。

底线是:

我需要能够动态地(以编程方式)设置sciluigi.Parameter对象,然后能够区分sciluigi.Parameter()对象变量(如out)和“真实”str()对象(如in_target

我希望这是有道理的。

2 个答案:

答案 0 :(得分:0)

接受并默默地丢弃构造函数中的参数,如下所示:

class FileConverter(sciluigi.Task):
    def __init__(self, *_args, **_kwargs):
        self.var = 'anything'

答案 1 :(得分:0)

仅供将来参考,回答孤立的问题,“如何...

setattr(<thisClassObject>, 'DynamicVar', sciluigi.Parameter(default='Yes') )

是否使用内置locals()功能。即。

locals()['DynamicVar'] = sciluigi.Parameter(default='Yes') #String only

这是我如何解决我的特殊kluge的片段;)

deleteme.py

import sciluigi

class MyFooWriter(sciluigi.Task):
    locals()['outfile'] = sciluigi.Parameter(default='./foo.txt') #String only
    locals()['normalvar'] = 'Normalstring'
    print "pre-self-returned outfile type =", type(outfile)
    print "pre-self-returned normalvar type =", type(normalvar)
#     locals()['param1'] = 
    def out_foo(self):
        # raw_input("Enter...")
        return sciluigi.TargetInfo(self, self.outfile)

    def run(self):
        print "self.outfile type =", type(self.outfile)
        print "self.normalvar type =", type(self.normalvar)
        # raw_input("Enter...")        
        with self.out_foo().open('w') as foofile:
            foofile.write('foo\n')            


class MyWorkflow(sciluigi.WorkflowTask):
    def workflow(self):
        print 'Starting workflow...'
        foowriter = self.new_task('foowriter', MyFooWriter, outfile = 'testfile.txt')
        return foowriter        

if __name__ == '__main__':
    sciluigi.run_local(main_task_cls=MyWorkflow)  

输出

pre-self-returned outfile type = <class 'sciluigi.parameter.Parameter'>
pre-self-returned normalvar type = <type 'str'>
Starting workflow...
2017-02-27 12:08:37 |     INFO | --------------------------------------------------------------------------------
2017-02-27 12:08:37 |     INFO | SciLuigi: MyWorkflow Workflow Started (logging to log/workflow_myworkflow_started_20170227_110837_278707.log)
2017-02-27 12:08:37 |     INFO | --------------------------------------------------------------------------------
2017-02-27 12:08:37 |     INFO | Task foowriter started
self.outfile type = <type 'str'>
self.normalvar type = <type 'str'>
2017-02-27 12:08:37 |     INFO | Task foowriter finished after 0.001s
Starting workflow...
2017-02-27 12:08:37 |     INFO | --------------------------------------------------------------------------------
2017-02-27 12:08:37 |     INFO | SciLuigi: MyWorkflow Workflow Finished (workflow log at log/workflow_myworkflow_started_20170227_110837_278707.log)
2017-02-27 12:08:37 |     INFO | --------------------------------------------------------------------------------