【发布时间】:2020-04-08 01:44:46
【问题描述】:
我正在尝试让 Visual Studio Code 格式化(颜色而不是布局)带有类型注释(提示)的 Python 代码。以下代码没有这样做:
from typing import Iterator
# return math.factorial(x)
def fib(n: int) -> Iterator[int]:
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
"""
This function checks whether a string is a palindrome.
s - The string to check.
"""
def is_palindrome(s: str) -> bool:
return s == s[::-1]
"""
This function compares two strings of word letters and returns the percentage match.
p_string1 - The first letters to compare.
p_string2 - The second letters to compare.
"""
def compare_letters(p_string1: str, p_string2: str) -> float:
return 1.0
我正在使用"python.formatting.provider": "black",但我也尝试过autopep8 和yapf。他们似乎都以同样的方式失败了,因为在类型注释之后把它们都搞混了。
当我访问 black 网站并将代码粘贴到 Black Playground 时,它工作正常。
我已使用 python -m pip install --upgrade black 进行升级,它显示的版本 (black-19.10b0) 与 Black Playground 相同,因此不确定这是 Visual Studio Code 问题还是我的问题。
我正在使用WinPython 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32。
不确定要针对所有这些 linting、格式(颜色/布局)、Python 解析等记录错误。
有没有人成功地在 Visual Studio Code 中格式化 Python 类型注释以及您使用什么设置?
更新:当我使用code --disable-extensions 运行时,不会发生这种情况。有谁知道我如何有选择地禁用扩展程序以找出导致问题的原因?
【问题讨论】:
-
您期望的结果是什么?除了将文档字符串放在错误的位置(它们应该在
def行下并缩进一个级别)之外,我没有看到任何格式不正确的内容。 -
只需将其粘贴到 VSC 中,即使更正了文档字符串,您也会看到所有颜色都出现错误。
-
根据上面的示例代码,语法突出显示对我来说很好。 “以同样的方式失败”的意思可以更具体吗?你看到的失败是什么?我刚刚使用 Black 使用 Python 扩展在 VS Code 中运行了您的代码,并对其进行了适当的重新格式化。
-
Iterator[int]:之后,除了偶尔出现的 2 种颜色外,几乎所有东西都是白色的。while、yield、def和return等关键字并不是应有的蓝色。docstrings不是灰色的。comments不是绿色的,等等。你能分享你正在使用的设置吗? -
我已经更新了您的标题,使其更具解释性。基本上语法高亮是 VS Code 的事情,而不是扩展的事情。我会尝试更改您的主题,看看这是否会导致不同的输出,因为他们都选择了他们想要突出显示的内容并且他们并不都同意什么是重要的。
标签: python python-3.x visual-studio-code