Dev Python (Django) with VSCode
บันทึกไว้ซะหน่อย หลังจาก setup เครื่องใหม่แบบเกือบคลีนๆ ต้องมาลง VSCode และ Setup ใหม่ทั้งหมด ได้โอกาสทบทวนไปในตัว จริงๆ ไม่มีอะไรมาก ผมใช้แค่ตัวจัด format และ ตรวจสอบ syntax เบื้องต้นด้วย pylint เริ่มกันเลย
ติดตั้ง Python3
ใน macOS จะมี Python2.7 ให้มาแต่จะใช้ Python3 ก็ทำการติดตั้งก่อนเลย
$ brew install python3
ติดตั้ง virtualenv
$ pip3 install virtualenv
สร้าง virtualenv ไว้สำหรับ VSCode
$ virtualenv -p python3 ~/venv
ใช้ venv ที่สร้างไว้
$ . ~/venv/bin/activate
ติดตั้ง Pylint
สำหรับตรวจสอบความถูกต้องต่างๆ รวมไปถึง format ด้วย
(venv) $ pip install pylint
ติดตั้ง yapf
สำหรับจัด format code แบบอัตโนมัติให้เรา
(venv) $ pip install yapf
ถ้าพัฒนา Django ก็ติดตั้งเพิ่มได้เลย
(venv) $ pip install django pylint_django
ติดตั้งสิ่งที่ต้องการเรียบร้อยแล้วก็เปิด VSCode ขึ้นมาทำการ config ให้ใช้งานดังนี้
ติดตั้ง Python for VSCode Extension
เปิดเมนู Code → Preferences → Settings
แล้วแก้ไข settings ทางฝั่ง USER SETTINGS
{"editor.quickSuggestions": true,"editor.acceptSuggestionOnEnter": "on","editor.quickSuggestionsDelay": 10,"editor.wordBasedSuggestions": true,"editor.parameterHints": true,"editor.formatOnSave": true,"python.venvPath": "/Users/mrchoke/venv","python.pythonPath": "/Users/mrchoke/venv/bin/python","python.linting.pylintArgs": ["--load-plugins","pylint_django","--max-line-length=120"],"python.linting.pylintEnabled": true,"python.linting.pylintPath": "/Users/mrchoke/venv/bin/pylint","python.formatting.formatOnSave": true,"python.formatting.provider": "yapf","python.formatting.yapfArgs": ["--style","{based_on_style: chromium, indent_width: 4}"],"python.formatting.yapfPath": "/Users/mrchoke/venv/bin/yapf"}
ตั้ง path ให้ตรงกับ venv ที่เราติดตั้งไว้ จริงๆ ถ้าใครไม่ใช้ virtualenv ก็ได้นะครับ ก็อ้างอิง path ไปให้ตรงก็ได้เช่นกัน ส่วนค่าต่างๆ ก็ปรับตามใจชอบ เวลาเราพิมพ์ code ลงไปมันก็จะมีการ suggestion ให้เวลา save ก็จัด format ให้ลองดูครับ ผมก็มือใหม่เช่นกัน หวังว่าเป็นบันไดให้ก้าวขึ้นเป็นระดับเทพกันต่อไปครับ
ทดสอบ
auto suggestion / auto completion
pylint
auto formatting
ผมใช้ตัวอย่าง code ทดสอบจาก https://pypi.python.org/pypi/yapf
ลอง copy ไปแปะใน VSCode เมื่อทำการ save format ควรถูกจัดให้สวยงามตามภาพตัวอย่าง
x = { 'a':37,'b':42,
'c':927}
y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo ( object ):
def f (self ):
return 37*-+2
def g(self, x,y=42):
return y
def f ( a ) :
return 37+-+a[42-x : y**3]