filelock icon indicating copy to clipboard operation
filelock copied to clipboard

Mypy reports "filelock.FileLock is not valid as a type"

Open domdfcoding opened this issue 3 years ago • 1 comments

I have some code that uses filelock, and is annotated something like this:

from typing import Optional
from filelock import FileLock

reveal_type(FileLock)
lock: Optional[FileLock] = None

mypy previously ignored the FileLock object as there were no type annotations in the package. However, mypy now reports the following:

t.py:4: note: Revealed type is "Type[filelock._api.BaseFileLock]"
t.py:5: error: Variable "filelock.FileLock" is not valid as a type
t.py:5: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

If I add an __init__.pyi file to the filelock package mypy seems happier:

# filelock/__init__.pyi
from ._api import BaseFileLock

FileLock = BaseFileLock
t.py:4: note: Revealed type is "def (lock_file: Union[builtins.str, os.PathLike[Any]], timeout: builtins.float =) -> filelock._api.BaseFileLock"
Success: no issues found in 1 source file

Not sure what the best solution is.

domdfcoding avatar May 10 '22 17:05 domdfcoding

Have you tried :

my_lock:filelock.BaseFileLock = filelock.FileLock(string)

?

Edit: @domdfcoding

axoroll7 avatar Aug 21 '22 08:08 axoroll7