Question Details

No question body available.

Tags

python pycharm python-typing

Answers (2)

July 4, 2026 Score: 3 Rep: 791,184 Quality: Low Completeness: 40%

It looks like PyCharm isn't able to infer that the if filename: statement means that the None case isn't possible in its body. Try adding a new variable with a more restricted type.

if filename: fn: str = filename with open("files\\" + fn, "wb") as f: pass
July 5, 2026 Score: 3 Rep: 418 Quality: Low Completeness: 50%

The following line is interfering how the static type checker infers the type:

filename = filename

Because no warning will be shown after its removal.

Since we are certain filename won't be None inside the if block, we just need to make sure static type checker also knows that. We can use assert to enforce it.

Your code would not be flagged with that warning after the change, like so:

filename: str | None = None

if filename: # i.e. not None filename = filename assert filename is not None # added to enforce the fact that it's not None with open("files\\" + filename, "wb") as f: pass