Mypy: False positive: Path(os.getenv("TEMP"))

Created on 26 Nov 2019  路  4Comments  路  Source: python/mypy

Please provide more information to help us understand the issue:

  • Are you reporting a bug, or opening a feature request?
    A bug

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

import os
from pathlib import Path

Path(os.getenv("TEMP"))
  • What is the actual behavior/output?
me:~/cia> mypy Bug.py
Bug.py:4: error: Argument 1 to "Path" has incompatible type "Optional[str]"; expected "Union[str, _PathLike[str]]"
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?
    No error

  • What are the versions of mypy and Python you are using?

mypy==0.740
mypy-extensions==0.4.3
Python 3.7.5 (default, Nov 22 2019, 15:39:42) 
[GCC 7.4.1 20190905 [gcc-7-branch revision 275407]] on linux
  • What are the mypy flags you are using? (For example --strict-optional)
    None.

Most helpful comment

So either
Path(os.getenv("PWD", default="..."))
or adding

PWD = os.getenv(...)
if PWD is None:
  raise
Path(PWD)

seem to be fixing this non-issue. That's pretty smart for a linter.

All 4 comments

>>> import os
>>> from pathlib import Path
>>> 
>>> Path(os.getenv("TEMP"))
Traceback (most recent call last):
    ...
TypeError: expected str, bytes or os.PathLike object, not NoneType

Hmm... @ilevkivskyi , I think I should have said that I am on Windows where TEMP is defined. On Linux, make the code work by replacing TEMP by, e.g., PWD:

import os
from pathlib import Path
Path(os.getenv("PWD"))

This runs fine. Surely the mypy error is not due to the string returned by os.getenv could be None in few edge cases? (Or is it - is that the Optional?)

Optional[X] is literally just Union[X, None].

So either
Path(os.getenv("PWD", default="..."))
or adding

PWD = os.getenv(...)
if PWD is None:
  raise
Path(PWD)

seem to be fixing this non-issue. That's pretty smart for a linter.

Was this page helpful?
0 / 5 - 0 ratings