pythonpython-stackless

stackless python constructor


import stackless
class MyTasklet(stackless.tasklet):
    def __init__(self, func, msg):
        pass

def foo():
    pass

msg = 'hello'
MyTasklet(foo, msg)()

I am using stackless python, this code generates the following error:

Traceback (most recent call last):
  File "E:/workspace/python/test/klass.py", line 11, in <module>
    MyTasklet(foo, msg)()
TypeError: tasklet() takes at most 1 argument (2 given)

It's very odd since I did not call the constructor of stackless.tasklet.

Anyone know what exactly the error is about.


Solution

  • Since the problem has to do with sub-classing stackless.tasklet, you could just make MyTasklet a callable object instead like follows:

    import stackless
    class MyTasklet(object):
        def __init__(self, func, msg):
            self.func = func
            self.msg = msg 
    
        def __call__(self):
          t = stackless.tasklet()
          t.bind(self.func)
          t.setup(self.msg)
          t.run()
    
    def foo(msg):
      print msg 
    
    msg = 'hello'
    MyTasklet(foo, msg)()
    

    EDIT: Alternatively you can just override __new__ to pass the correct arguments to stackless.tasklet.__new__:

    import stackless
    class MyTasklet(stackless.tasklet):
      def __new__(cls, func, msg):
        return stackless.tasklet.__new__(MyTasklet, func)
      def __init__(self, func, msg):
        pass
    
    def foo():
      pass
    
    msg = 'hello'
    MyTasklet(foo, msg)()