thombashi / pathvalidate

A Python library to sanitize/validate a string such as filenames/file-paths/etc.
https://pathvalidate.rtfd.io/
MIT License
220 stars 13 forks source link

Type model is incorrect #29

Closed rogalski closed 1 year ago

rogalski commented 1 year ago

Typing of pathvalidate is incorrect. It uses Union for input/output arguments instead of using generics. This throws mypy off - it cannot infer exact type of output variable, even if it's easily inferable from code structure.

repro.py

import pathlib
import typing

import pathvalidate

print(pathvalidate.__version__)

s = pathvalidate.sanitize_filename("lorem_ipsum")
print(type(s))
if typing.TYPE_CHECKING:
    reveal_type(s)

p = pathvalidate.sanitize_filename(pathlib.Path("lorem_ipsum"))
print(type(p))
if typing.TYPE_CHECKING:
    reveal_type(p)

Outputs:

$ python3 repro.py 
2.5.0
<class 'str'>
<class 'pathlib.PosixPath'>
$ mypy repro.py 
repro.py:11: note: Revealed type is "Union[builtins.str, pathlib.Path]"
repro.py:16: note: Revealed type is "Union[builtins.str, pathlib.Path]"
Success: no issues found in 1 source file

Expected output: str type inferred for first reveal_type, pathlib.Path inferred for second reveal_type

thombashi commented 1 year ago

Thank you for your report. f7f5c8f fixed the problem.

mypy issue29.py --python-version 3.7
issue29.py:11: note: Revealed type is "builtins.str"
issue29.py:16: note: Revealed type is "pathlib.Path"