Python in Visual Studio Code

ติดตั้ง Python – Visual Studio Marketplace (จะติดตั้ง Pylance – Visual Studio Marketplace ให้ด้วยเลย)

  1. Inlay Type Hints
  2. Code Style Checking
  3. Linting Python

1. Inlay Type Hints

กด Ctrl + Shit + p พิมพ์ว่า Preferences: Open Settings แล้วเลือกระดับ Workspace จะได้ไฟล์ .vscode\settings.json

ให้เพิ่ม 2 บรรทัดที่ไฟล์ settings.json

{
    ...
    "python.analysis.inlayHints.functionReturnTypes": true, 
    "python.analysis.inlayHints.variableTypes": true
}

สร้างไฟล์ test.py ดังนี้

import time
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)
def main(test_times=50):
    start = time.time()
    for _ in range(test_times):
        fib(30)
    print(f"Total time spent: {time.time() - start} s")

main()

จะเห็น Type Hints แบบนี้

2. Code Style Checking

ตรวจสอบด้วย flake8 (pypi.org/project/flake8/)

ติดตั้ง flake8

> pip install flake8

ตรวจสอบ Code Style ด้วย flake8

flake8 path/to/code/to/check.py
# or
flake8 path/to/code/
> python -m flake8 test.py
test.py:2:1: E302 expected 2 blank lines, found 0
test.py:6:1: E302 expected 2 blank lines, found 0
test.py:12:1: E305 expected 2 blank lines after class or function definition, found 1
test.py:12:7: W292 no newline at end of file

1. แก้ไข Code Style ด้วยมือ!!

อ่านได้ที่

2. แก้ไข Code Style ด้วย VSCode

โดยทำการ Format Document With … แล้วเลือก autopep8

ครั้งต่อไปก็ Format Document โดยกด Shift + Alt + F ได้เลย

import time


def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)


def main(test_times=50):
    start = time.time()
    for _ in range(test_times):
        fib(30)
    print(f"Total time spent: {time.time() - start} s")


main()

ตรวจสอบ Code Style ด้วย flake8 อีกรอบจะผ่านละ

> python -m flake8 test.py

3. แก้ไข Code Style ด้วย black

ติดตั้ง black (pypi.org/project/black/)

> pip install black

ทำการ reformat ด้วย black (จะได้เหมือน reformat ด้วย VSCode เลย)

> python -m black test.py  
reformatted test.py

All done! ✨ 🍰 ✨
1 file reformatted.

ตรวจสอบ Code Style ด้วย flake8 ก็จะผ่าน

3. Linting Python

เลือก linter (Pylint, flake8, mypy) เราเลือกติดตั้ง Pylint (https://marketplace.visualstudio.com/items?itemName=ms-python.pylint)

Run linting

Linting will automatically run when a Python file is opened or saved.

Errors and warnings are shown in the Problems panel (Ctrl+Shift+M) for open files, and are also highlighted in the code editor. Hovering over an underlined issue displays the details: