简体   繁体   中英

Using python multiprocessing.Lock as an argument type in mypy

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM