Using python multiprocessing.Lock as an argument type in mypy

Viewed 303

I have a python function that takes in a multiprocessing.Lock object as an input and uses the acquire and release functions on it. Evaluating it with mypy returns the error Function multiprocessing.Lock" is not valid as a type. How can I properly annotate this function?

1 Answers

Lock is actually a plain function that returns a _LockType, which is defined as _LockType = synchronize.Lock, so you can do:

from multiprocessing.synchronize import Lock as LockBase

def func(lock: LockBase):
    pass

Although, the fact that they have _LockType as module private suggests they're treating it as an implementation detail that may change in the future, so be careful.


There's also this comment block above where _LockType is defined:

# The following type aliases can be used to annotate the return values of
# the corresponding functions. They are not defined at runtime.
#
# from multiprocessing import Lock
# from typing import TYPE_CHECKING
# if TYPE_CHECKING:
#     from multiprocessing import _LockType
# lock: _LockType = Lock() 
. . .
_LockType = synchronize.Lock
Related