3

I want to check that a a variable e is an instance of threading.Event. However, when I create e, it actually creates a protected class instance threading._Event. For example:

import threading
e = threading.Event()
assert type(e) == threading.Event   # raises AssertionError
assert type(e) == threading._Event  # succeeds

Asserting that it is a protected class instance seems un-pythonic. Would assert type(e) == type(threading.Event()) be better? Would another option be better yet?

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
ericksonla
  • 1,247
  • 3
  • 18
  • 34
  • `threading.Event` is not a class. The documentation describes it as a factory function. – user2357112 Feb 01 '17 at 17:34
  • ...oh goddammit, this is another case of conflicting documentation. Some parts of the docs actually do call it a class. At least the 3.3+ docs are correct (since it actually became a class at that point). – user2357112 Feb 01 '17 at 17:35
  • If you want to perform an explicit type check, I'd use `type(threading.Event())` and save that to a variable. – user2357112 Feb 01 '17 at 17:39
  • 1
    `assert type(e) == threading.Event` works in Python 3 but `assert type(e) == threading._Event` doesn't (`_Event` not recognized) – Jacques Gaudin Feb 01 '17 at 17:39
  • @user2357112 Why save it to a variable instead of just use it and delete it as in my example? – ericksonla Feb 01 '17 at 17:41
  • @ericksonla: To avoid creating tons of event objects. I don't know how heavyweight those are, and future readers of the code likely won't know either. – user2357112 Feb 01 '17 at 17:42
  • @user2357112 Why won't it be deleted immediately after the line its created? – ericksonla Feb 01 '17 at 17:44
  • @ericksonla: The worry isn't that the event objects will stick around and hog resources; the worry is that the act of creating them might be expensive. – user2357112 Feb 01 '17 at 17:48

1 Answers1

0

Have a look at this answer about subclassing threading.Event.

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)

Since 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()

This was changed in Python 3:

class Event: """Class implementing event objects. 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. The flag is initially false. """

Community
  • 1
  • 1
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75