4

I'm trying to use the StoppableThread class presented as an answer to another question:

import threading

# Technique for creating a thread that can be stopped safely
# Posted by Bluebird75 on StackOverflow
class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

However, if I run something like:

st = StoppableThread(target=func)

I get:

TypeError: __init__() got an unexpected keyword argument 'target'

Probably an oversight on how this should be used.

Community
  • 1
  • 1
OregonTrail
  • 8,594
  • 7
  • 43
  • 58

2 Answers2

5

The StoppableThread class does not take or pass any additional arguments to threading.Thread in the constructor. You need to do something like this instead:

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self,*args,**kwargs):
        super(threading.Thread,self).__init__(*args,**kwargs)
        self._stop = threading.Event()

This will pass both positional and keyword arguments to the base class.

isedev
  • 18,848
  • 3
  • 60
  • 59
1

You are overriding init and your init doesn't take any arguments. You should add a "target" argument and pass it through to your base class constructor with super or even better allow arbitrary arguments via *args and *kwargs.

I.e.

def __init__(self,*args,**kwargs):
    super(threading.Thread,self).__init__(*args,**kwargs)
    self._stop = threading.Event()
Bernhard Kausler
  • 5,119
  • 3
  • 32
  • 36