Search code examples
pythonpython-multiprocessingpython-multithreadingstandard-libraryfactory-method

How to test if an object is a lock?


How would you test if an object is a threading.Lock or multiprocessing.Lock (and their respective RLocks?). These objects in Python (3, at least) are factory methods, so you can't just do:

isinstance(obj, threading.Lock)

As this would give:

TypeError: isinstance() arg 2 must be a type or tuple of types

Solution

  • If you have an instance, you can get its type. So the simple solution is to do

    threading_Lock = type(threading.Lock())
    isinstance(obj, threading_Lock)