Search code examples
pythonmultithreadingunit-testingtypesattributeerror

python - AttributeError: 'module' object has no attribute 'lock'


As part of my unit testing procedure i'm evaluating the type of a variable which has been returned from a certain method. The method returns a variable of type 'thread.lock' and I would like to test for this in the same way I test for variables of type 'str' or 'int' etc

This is the example carried out in the python 2.7.6 shell

>>> import threading, thread
>>> mylock = threading.Lock()
>>> type(mylock)
<type 'thread.lock'>
>>> type(mylock) is thread.lock

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    type(mylock) is thread.lock
AttributeError: 'module' object has no attribute 'lock'

I expected it to return True as shown in the second example

>>> myint = 4
>>> type(myint)
<type 'int'>
>>> type(myint) is int
True
>>> 

Please any solutions on how to get around this will be highly appreciated. Thanks


Solution

  • Instead of thread.lock use thread.LockType:

    >>> import threading, thread
    >>> mylock = threading.Lock()
    >>> type(mylock)
    <type 'thread.lock'>
    >>> thread.LockType
    <type 'thread.lock'>
    >>> type(mylock) is thread.LockType
    True
    

    But it is preferable to use isinstance():

    >>> isinstance(mylock, thread.LockType)
    True