4

My code contains what seems to be common practise, using:

import threading
mylock = threading.Lock()

def myfunction():
    with mylock:
        do_something()

But my PEP8 pylinter is squawking about:

Context manager 'lock' doesn't implement __enter__ and __exit__

Is there something I'm doing wrong in this code? I could just ignore the error, as I haven't seen any issues thus far, but I'd prefer to not just ignore & hope. I read on another post about the documentation for the __enter__ and __exit__, so I assume they must actually exist in some form.

Community
  • 1
  • 1
jhaagsma
  • 2,414
  • 2
  • 24
  • 26

1 Answers1

1

Context managers ensure some initialization and/or finilization of an object through __enter__ and __exit__ methods respectively. The with clause guarantees to execute these.

For example opening a file does not have any special initialization but the importtant finilization of closing file after use not to reduce the capacity of the process to open as much files as possible (saving for a rainy day!!!). Likewise Lock objects do not have any important initilization but the finilization of releasing the lock is crucial not to block any code wich depends on the aquiring of the lock.

Unfortunately Lock class does not implement context manager so using a lock in a with statement does not help you to release it. So you are responsible to release the lock in your code even an exception occurs.

Megacodist
  • 132
  • 5