3

In Python 2.7.5:

from threading import Event

class State(Event):
    def __init__(self, name):
        super(Event, self).__init__()
        self.name = name

    def __repr__(self):
        return self.name + ' / ' + self.is_set()

I get:

TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str

Why?

Everything I know about threading.Event I learned from: http://docs.python.org/2/library/threading.html?highlight=threading#event-objects

What does it mean when it says that threading.Event() is a factory function for the class threading.Event ??? (Uhh... just looks like plain old instanciation to me).

Scruffy
  • 908
  • 1
  • 8
  • 21
  • I just found http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python and am currently reading it. – Scruffy Aug 01 '13 at 15:54

2 Answers2

5

threading.Event is not a class, it's function in threading.py

def Event(*args, **kwargs):
    """A factory function that returns a new event.

    Events manage a flag that can be set to true with the set() method and reset
    to false with the clear() method. The wait() method blocks until the flag is
    true.

    """
    return _Event(*args, **kwargs)

Sinse this function returns _Event instance, you can subclass _Event (although it's never a good idea to import and use underscored names):

from threading import _Event

class State(_Event):
    def __init__(self, name):
        super(Event, self).__init__()
        self.name = name

    def __repr__(self):
        return self.name + ' / ' + self.is_set()
Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
  • 2
    http://docs.python.org/2/library/threading.html?h says "class threading.Event". Kinda misleading. I guess I'll have to start getting used to opening up the actual python source files. I used to find that intimidating but I probably know enough Python now for it to be helpful. – Scruffy Aug 01 '13 at 16:00
0

according to docs.python.org Changed in version 3.3: Event has been changed from a factory function to a class. so you can subclass Event and make your own Event instance.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 27 '23 at 20:11