Erroneous flagging of parentheses in "with" statement in Python 3.9 and below; valid parentheses are flagged
Environment data
- Language Server version: Pylance 2021.2.4
- OS and version: macOS Big Sur
- Python version: 3.8.7 from nix (
nix-env -iA nixpkgs.python38Full) with an environment created by Poetry
Code Snippet
from pathlib import Path
with (Path(".") / "file.txt").open() as f:
print(f)
Expected behaviour
Nothing; this is valid code in Python 3.8.
Actual behavior
Pylance gives the error Parentheses within "with" statement requires Python 3.10 or newer. This is an incorrect interpretation of parenthesized context managers; this parenthesization has always been allowed.
Logs
Where do I find these? I'm not seeing a large amount of info in any output panels.
Thanks for the bug report. This will be fixed in the next release.
This issue has been fixed in version 2021.3.0, which we've just released. You can find the changelog here: https://github.com/microsoft/pylance-release/blob/main/CHANGELOG.md#202130-3-march-2021
I am still seeing this in 2021.4.0 with Python 3.9.4

The code works and executes correctly:
with (HyperProcess(Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU) as hyper_proc,
Connection(
hyper_proc.endpoint,
hyper_path,
CreateMode.CREATE_IF_NOT_EXISTS,
{'lc_time': 'en_US', 'date_style': 'YMD'}
) as hyper_conn):
Thanks for the bug report. This is indeed a bug, but it's different from the previous one. The previous one involves the use of a call expression where the LHS is parenthesized.
Your example involves the use of a parenthesized tuple. According to the documented Python grammar, parenthesized tuples are not allowed in a with statement (in versions of Python prior to 3.9). I based the implementation of Pylance on this documentation, but it appears that the documentation is wrong. I'll adjust the Pylance implementation accordingly.
Actually, I take that back. This code generates a runtime exception when I run it in versions of Python prior to 3.9, so the documentation is correct. It appears that this restriction was removed in Python 3.9, not in 3.10. (I was mislead by this documentation which indicates that 3.10 removed this limitation.) I'll change the check to allow parentheses for 3.9 as well.
This will be fixed in the next release of Pylance.
Wow - thanks for a quick fix! I wish commercial software companies had this kind of turn-around ;)
This issue has been fixed in version 2021.4.1, which we've just released. You can find the changelog here: https://github.com/microsoft/pylance-release/blob/main/CHANGELOG.md#202141-14-april-2021
Hi, I've encountered the same problem on v2021.8.1: The code
with (await self._lock_device(device)):
causes the error message from pylance.
This issue has already been fixed. If you think that you are seeing a related problem, please open a new issue with a self-contained sample that repros the problem. Thanks!