<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>pep8 彙整 - 台大系統訓練班課程網頁 (林奇賦)</title>
	<atom:link href="http://cflin.com/wordpress/tag/pep8/feed" rel="self" type="application/rss+xml" />
	<link>http://cflin.com/wordpress</link>
	<description>台大系統訓練班 python 課程相關資料</description>
	<lastBuildDate>Tue, 05 Dec 2017 10:20:49 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.8.3</generator>

<image>
	<url>http://cflin.com/wordpress/wp-content/uploads/2017/12/cropped-2000px-Python-logo-notext.svg_-32x32.png</url>
	<title>pep8 彙整 - 台大系統訓練班課程網頁 (林奇賦)</title>
	<link>http://cflin.com/wordpress</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>PEP8 Python 編碼規範手冊</title>
		<link>http://cflin.com/wordpress/603/pep8-python%e7%b7%a8%e7%a2%bc%e8%a6%8f%e7%af%84%e6%89%8b%e5%86%8a</link>
					<comments>http://cflin.com/wordpress/603/pep8-python%e7%b7%a8%e7%a2%bc%e8%a6%8f%e7%af%84%e6%89%8b%e5%86%8a#respond</comments>
		
		<dc:creator><![CDATA[Chifu]]></dc:creator>
		<pubDate>Tue, 05 Dec 2017 10:15:03 +0000</pubDate>
				<category><![CDATA[Python範例]]></category>
		<category><![CDATA[pep8]]></category>
		<category><![CDATA[python範例]]></category>
		<guid isPermaLink="false">http://cflin.com/wordpress/?p=603</guid>

					<description><![CDATA[<p>PEP 8 介紹 PEP8 是 Python 社群共通的風格指南，一開始是 Python 之父 Guido van Rossum 自己的撰碼風格，慢慢後來演變至今，目的在於幫助開發者寫出可讀性高且風格一致的程式。許多開源計畫，例如 Django 、 OpenStack等都是以 PEP8 為基礎再加上自己的風格建議。 程式碼編排 (Code lay-out) 這邊列出PEP8裡面的重點，有興趣可以直接看官方原文的文件會更清楚一些。 縮排 (Indentation) 每層縮排使用 4 個空格 斷行風格 正確： # 斷行首字母與開頭的括號垂直對齊. # 垂直縮排，首行不能有參數. # 垂直縮排，後面還有其它代碼時，需要添加一層額外的縮排加以區別： 錯誤： # 垂直縮排方式首行不能有引數 # 垂直縮排，首行不能有參數; 後面還有其它代碼部分時，斷行要添加一層縮進，使其與其它代碼部分能區別開來 if 條件斷行 if ( 剛好有 4 個字符，相當於一層縮排。 對於 if 條件斷行，以下幾種風格都可以： 沒有額外的縮排 添加註釋加以區分 添加額外的縮排加以區分 多行的括號 括號結束符與最後行的首字符對齊，如： 括號結束符與首行的首字符對齊, 如： 上面兩種排版的方式都可以 &#8230; <a href="http://cflin.com/wordpress/603/pep8-python%e7%b7%a8%e7%a2%bc%e8%a6%8f%e7%af%84%e6%89%8b%e5%86%8a" class="more-link">閱讀全文 <span class="screen-reader-text">PEP8 Python 編碼規範手冊</span> <span class="meta-nav">&#8594;</span></a></p>
<p>這篇文章 <a rel="nofollow" href="http://cflin.com/wordpress/603/pep8-python%e7%b7%a8%e7%a2%bc%e8%a6%8f%e7%af%84%e6%89%8b%e5%86%8a">PEP8 Python 編碼規範手冊</a> 最早出現於 <a rel="nofollow" href="http://cflin.com/wordpress">台大系統訓練班課程網頁 (林奇賦)</a>。</p>
]]></description>
										<content:encoded><![CDATA[<h1>PEP 8 介紹</h1>
<p><a href="http://legacy.python.org/dev/peps/pep-0008/">PEP8</a> 是 Python 社群共通的風格指南，一開始是 Python 之父 Guido van Rossum 自己的撰碼風格，慢慢後來演變至今，目的在於幫助開發者寫出可讀性高且風格一致的程式。許多開源計畫，例如 <a href="https://docs.djangoproject.com/en/1.6/internals/contributing/writing-code/coding-style/">Django</a> 、 <a href="http://docs.openstack.org/developer/hacking/">OpenStack</a>等都是以 PEP8 為基礎再加上自己的風格建議。</p>
<h2>程式碼編排 (Code lay-out)</h2>
<p>這邊列出PEP8裡面的重點，有興趣可以直接看官方原文的文件會更清楚一些。</p>
<p><strong>縮排 (Indentation)</strong><br />
每層縮排使用 4 個空格</p>
<p><strong>斷行風格</strong><br />
正確：<br />
# 斷行首字母與開頭的括號垂直對齊.</p>
<pre class="brush: python; title: ; notranslate">
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
</pre>
<p># 垂直縮排，首行不能有參數.</p>
<pre class="brush: python; title: ; notranslate">
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)
</pre>
<p># 垂直縮排，後面還有其它代碼時，需要添加一層額外的縮排加以區別：</p>
<pre class="brush: python; title: ; notranslate">
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
</pre>
<p>錯誤：<br />
# 垂直縮排方式首行不能有引數</p>
<pre class="brush: python; title: ; notranslate">
foo = long_function_name(var_one, var_two,
    var_three, var_four)
</pre>
<p># 垂直縮排，首行不能有參數; 後面還有其它代碼部分時，斷行要添加一層縮進，使其與其它代碼部分能區別開來</p>
<pre class="brush: python; title: ; notranslate">
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)
</pre>
<p><strong>if 條件斷行</strong><br />
<span style="color: #ff0000;">if (</span> 剛好有 4 個字符，相當於一層縮排。<br />
對於 if 條件斷行，以下幾種風格都可以：<br />
沒有額外的縮排</p>
<pre class="brush: python; title: ; notranslate">
if (this_is_one_thing and
    that_is_another_thing):
    do_something()
</pre>
<p>添加註釋加以區分</p>
<pre class="brush: python; title: ; notranslate">
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()
</pre>
<p>添加額外的縮排加以區分</p>
<pre class="brush: python; title: ; notranslate">
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()
</pre>
<h3><strong>多行的括號</strong></h3>
<p>括號結束符與最後行的首字符對齊，如：</p>
<pre class="brush: python; title: ; notranslate">
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]

result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )
</pre>
<p>括號結束符與首行的首字符對齊, 如：</p>
<pre class="brush: python; title: ; notranslate">
my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)
</pre>
<p>上面兩種排版的方式都可以</p>
<h3><strong>使用Tab還是空格縮排</strong></h3>
<p>用空格</p>
<h4><strong>每行最長長度</strong></h4>
<p>所有行都不超過 80 個字符</p>
<p>限制編輯器視窗的寬度，使能並排同時打開多個文件。<br />
設置編輯器寬度(set width to 80)，來避免 wrapping<br />
對於較少結構限制的長文本（如 docstrings 或註釋），行長應限制為 72 個字符。<br />
如果團隊成員都同意使用長行，則可以將行長增加到不超過 100 個字符，但是 docstrings 和註釋還必須為 72 個字符。</p>
<p>有括號的長行可以用 implicit continuation 來斷行，其它的可以用 \ 來斷行，如：</p>
<pre class="brush: python; title: ; notranslate">
with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())
</pre>
<h4><strong>操作符要和操作數在一起</strong></h4>
<p># 推薦的正確的風格，這樣很容易將操作符與操作數匹配：</p>
<pre class="brush: python; title: ; notranslate">
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)
</pre>
<p># 這種風格現今已不推薦使用了：</p>
<pre class="brush: python; title: ; notranslate">
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)
</pre>
<h4><strong>空行分隔</strong></h4>
<p>模組中最頂層的函數和類定義都要用兩行空行分隔<br />
類別中的方法定義用單行分隔<br />
要把一組相關的函數分組，可以用一些額外的空行<br />
函數中的邏輯區塊可以加空行來分隔</p>
<h4><strong>原始碼的編碼</strong></h4>
<p>Python 核心模組文件的編碼都必須用 UTF-8（Python2 是 ASCII)。<br />
使用默認的編碼時（Python3: UTF-8，Python2: ASCII)，不能使用編碼聲明<br />
標準庫中，只有測試、作者名才能使用非默認的編碼，其它情況下的非 ASCII 字符用 \x, \u, \u, \N 表示法表示。</p>
<h4><strong>Import</strong></h4>
<p>每行 import 只導入一個模組：<br />
# 正確:<br />
import os<br />
import sys<br />
# 錯誤：<br />
import sys, os<br />
# 正確：同一模組中的內容可以在同一行導入<br />
from subprocess import Popen, PIPE</p>
<p>import 語句要在文件的前面，在模組註釋及 docstrings 之後，在模組全域變數和常數定義之前。<br />
import 分組及導入順序，每個分組之間用一行空行分隔 1. 標準庫 2. 相關第三方庫 3. 本地應用/庫的特殊導入<br />
推薦使用絕對導入，如：<br />
import mypkg.sibling<br />
from mypkg import sibling<br />
from mypkg.sibling import example</p>
<p>在比較覆雜的套件組成中，也可以用顯式的相對導入，如：<br />
from . import sibling<br />
from .sibling import example<br />
從一個模塊中導入一個類別時，要顯示拼寫出類別名，如：<br />
from myclass import MyClass<br />
from foo.bar.yourclass import YourClass</p>
<p>如果與本地名稱衝突，可以先導入模組：<br />
import myclass<br />
import foo.bar.yourclass<br />
然後使用："myclass.MyClass" 和 &#8220;foo.bar.yourclass.YourClass"。<br />
應該避免使用 from &lt;module&gt; import *<br />
模組層級的特殊名稱（如__all__)的位置：<br />
必須在模組的 docstrings 或註釋之後，但在任何的 import 語句之前。from __future__ 比較特殊，Python 強制該語句必須在 docstrings 或註釋之後，因此風格如下：</p>
<pre class="brush: python; title: ; notranslate">
&quot;&quot;&quot;This is the example module.

This module does stuff.
&quot;&quot;&quot;

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys
</pre>
<h4><strong>字符引號 (String Quotes)</strong></h4>
<p>單引號和雙引號的功能是等同的。<br />
對於多行字符串，應該用雙引號字符形式的三引號"""，以便與 PEP257 中的 docstrings 規範兼容</p>
<h4><strong>表達式和語句中的空格 (Whitespace in Expressions and Statements)</strong></h4>
<p>()、[]、{} 等括號內不要多餘的空格，如：<br />
# 正確：<br />
spam(ham[1], {eggs: 2})<br />
# 錯誤：<br />
spam( ham[ 1 ], { eggs: 2 } )<br />
,、;、: 之前不要有空格，如：<br />
# 正確：<br />
if x == 4: print x, y; x, y = y, x<br />
# 錯誤：<br />
if x == 4 : print x , y ; x , y = y , x<br />
在 slice 語句中的 :實際上是一個二元操作符，因此其兩側的空格數必須相同; 但當無 slice 參數時，兩側的空格可以都省略，如：<br />
# 以下是正確的風格：<br />
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]<br />
ham[lower:upper], ham[lower:upper:], ham[lower::step]<br />
ham[lower+offset : upper+offset]<br />
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]<br />
ham[lower + offset : upper + offset]<br />
# 以下是錯誤的風格：<br />
ham[lower + offset:upper + offset]<br />
ham[1: 9], ham[1 :9], ham[1:9 :3]<br />
ham[lower : : upper]<br />
ham[ : upper]<br />
函數調用的 () 及索引的 [] 前不要加空格，如：<br />
# 正確風格：<br />
spam(1)<br />
dct[&#8216;key&#8217;] = lst[index]<br />
# 錯誤風格：<br />
spam (1)<br />
dct [&#8216;key&#8217;] = lst [index]<br />
不要在賦值語句中加入額外的空格來對齊，如：<br />
# 正確的風格：<br />
x = 1<br />
y = 2<br />
long_variable = 3<br />
# 錯誤的風格:<br />
x = 1<br />
y = 2<br />
long_variable = 3</p>
<h4>其它推薦風格</h4>
<p>任何行的行尾都不要有空白符。<br />
在二元操作符號兩側一般都要加一個空格，一般的二元操作符號如：<br />
賦值: =, +=, -=<br />
比較：==, &lt;, &gt;, !=, &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not<br />
布林操作： and, or, not<br />
在分優先級的表達式中，在最低優先級的操作符兩側加一個空格，但至多只能加一個空格，如：<br />
# 正確的風格：<br />
x = x*2 &#8211; 1<br />
hypot2 = x*x + y*y<br />
c = (a+b) * (a-b)<br />
# 錯誤的風格：<br />
x = x * 2 &#8211; 1<br />
hypot2 = x * x + y * y<br />
c = (a + b) * (a &#8211; b)<br />
<strong>在關鍵字參數和默認參數值中的 = 兩側不要加空格</strong>，如：<br />
# 正確的風格：<br />
def complex(real, imag=0.0):<br />
return magic(r=real, i=imag)<br />
錯誤的風格：<br />
def complex(real, imag = 0.0):<br />
return magic(r = real, i = imag)<br />
<strong>函數註解中的 : 前不要加空格，這符合 : 的常規風格，但是 -&gt; 兩側要加空格</strong>，如：<br />
# 正確的風格：<br />
def munge(input: AnyStr): &#8230;<br />
def munge() -&gt; AnyStr: &#8230;<br />
# 錯誤的風格：<br />
def munge(input:AnyStr): &#8230;<br />
def munge()-&gt;PosInt: &#8230;<br />
<strong>參數註解中，如果註解的參數有默認值，指定默認值的 = 兩側要加空格</strong>，如：<br />
# 正確的風格：<br />
def munge(sep: AnyStr = None): &#8230;<br />
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): &#8230;<br />
# 錯誤的風格：<br />
def munge(input: AnyStr=None): &#8230;<br />
def munge(input: AnyStr, limit = 1000): &#8230;</p>
<p><strong>不要將多條語句組合在一行中</strong>，如：<br />
# 正確的風格：<br />
if foo == &#8216;blah&#8217;:<br />
do_blah_thing()<br />
do_one()<br />
do_two()<br />
do_three()<br />
# 錯誤風格：<br />
if foo == &#8216;blah&#8217;: do_blah_thing()<br />
do_one(); do_two(); do_three()</p>
<p># 如果 if/for/while 區塊內的程式碼很少，組合在一行有時還是可以接受的<br />
# 但是不推薦，如：<br />
if foo == &#8216;blah&#8217;: do_blah_thing()<br />
for x in lst: total += x<br />
while t &lt; 10: t = delay()<br />
# 但是在有多段語句時，絕對不能這樣，如：<br />
if foo == &#8216;blah&#8217;: do_blah_thing()<br />
else: do_non_blah_thing()</p>
<p>try: something()<br />
finally: cleanup()</p>
<p>do_one(); do_two(); do_three(long, argument,<br />
list, like, this)</p>
<p>if foo == &#8216;blah&#8217;: one(); two(); three()</p>
<h4><strong>註解 (Comments)</strong></h4>
<p>註解內容必須要和程式碼相關！<br />
註解應該是完整的語句，首字母一般大寫(英文)，一般要有句號。<br />
註解很短時句號可以省略。<br />
區塊註解一般由多個段落組成。用英文寫註解</p>
<h4><strong>區塊註解 (Block Comments)</strong></h4>
<p>每行用 # 及一個空格開始，如 #<br />
段落用一個只有 # 的行分隔</p>
<h4><strong>行內註解 (Inline Comments)</strong></h4>
<p>註解與語句內容至少用兩個空格分開，註解用 # 加一個空格開始<br />
# 不要像下面這樣，註解內容沒有必要<br />
x = x + 1 # Increment x<br />
# 但是有時，如下面的註解會很有用<br />
x = x + 1 # Compensate for border</p>
<h4>文件字串 (Documentation Strings)</h4>
<p>公開的模組、函數、類及方法都應該有文件字串，而非公開的方法可以用註解來代替，且註解放置在 def 行之後。<br />
多行的文件字串，結束符號要自成一行，如：</p>
<pre class="brush: python; title: ; notranslate">
&quot;&quot;&quot;Return a foobang

Optional plotz says to frobnicate the bizbaz first.
&quot;&quot;&quot;
</pre>
<p>單行的文件字串，結束符號和內容放在同一行</p>
<h4><strong>命名 (Naming Conventions)</strong></h4>
<p>沒有推薦的風格，但是別人要能從你的程式碼中看出你用的是什麽風格，常用的風格如下：</p>
<ul>
<li>b 單個小寫字母</li>
<li>B 單個大寫字母</li>
<li>lowercase</li>
<li>lower_case_with_underscores</li>
<li>UPPERCASE</li>
<li>UPPER_CASE_WITH_UNDERSCORES</li>
<li>CapitalizedWords, 這種風格中，對於縮寫詞應全部用大寫，如</li>
<li>HTTPServerError 比 HttpServerError 好</li>
<li>mixedCase<br />
Capitalized_Words_With_Underscores，這個太醜，不要用這種！</li>
<li>st_mode、st_mtime 等前綴，一般是系統接口返回，如果自己寫的程式碼不推薦用這種</li>
<li>_single_leading_underscore : 弱 “內部使用” 指示器，這種對象用 from M import * 不會被導入</li>
<li>single_trailing_underscore_ : 可以用來和 Python 關鍵詞進行區分，如 Tkinter.Toplevel(master, class_=&#8217;ClassName&#8217;)</li>
<li>__double_leading_underscore : 命名一個類屬性時，可以進行命名矯正，例如 class FooBar 內的 __boo 會變成 _FooBar__boo</li>
<li>double_leading_and_trailing_underscore : “magic” 對象，不要自己發明這種對象</li>
</ul>
<h4><strong>命名習慣 (Prescriptive: Naming Conventions)</strong></h4>
<ul>
<li>不用單個 l, O, I 等這樣的單個字符來命名，它們與數字1,0不好區分</li>
<li>套件名和模組名：全部用小寫，必要時可用 _，但不推薦，C/C++ 的擴展模組，如果其對應有 Python 版本，那麽 C/C++ 擴展模組名前加 _</li>
<li>類別名：用 CapWords 風格</li>
<li>異常名：用 CapWords 風格，一般應該有 Error 後綴</li>
<li>全域變數名：能用 from M import * 導入的變數全部放在 __all__ 中，或者全域變數用 _ 做前綴</li>
<li>函數名：應該用全部用小寫，單詞間可以用 _ 分隔，如 my_func，不推薦用 mixedCase 風格</li>
<li>函數和方法的參數：實例方法的第一個參數用 self, 類別方法的第一個參數用 cls，如果參數與關鍵字衝突，在參數名後加 _ 後綴，如 class_</li>
<li>實例變數和方法： 用小寫字符和 _, 非公開的實例變數和方法用一個 _ 做前綴; 避免與子類別中的名字衝突，類的變數可用兩個 _ 作前綴，例如 class FooBar 內的 __boo 會變成只能通過 FooBar._FooBar__boo 讀取</li>
<li>常數：全部大寫，可用 _ 分隔，如 MAX_OVERFLOW、TOTAL</li>
</ul>
<h3><strong>推薦的程式撰寫方式 (Programming Recommendations)</strong></h3>
<p>字符串連接不要用 a += b 或者 a = a + b, 用 &#8220;.join(), 後者性能更好。跟 None 的比較用 is 和 is not，不要用 ==，如果你想判斷 if x is not None, 不要縮寫成 if x 使用 if foo is not None，而不是 if not foo is None，前者更加易讀</p>
<p>如果要實現序列比較操作的話，應將 6 個操作（__eq__ , __ne__ , __lt__ , __le__ , __gt__ , __ge__）全部實現，可以借助 functools.total_ordering() 修飾器來減少工作量</p>
<p>將函數保存在一個變數中應該用 def f(x): return 2*x， 而非 f = lambda x: 2*x，後者不利於調試</p>
<p>自定義的異常類應該繼承至 Exception 類，而非 BaseException 類。Python 2 中拋出異常用 raise ValueError(&#8216;message&#8217;)，而非 raise ValueRoor, &#8216;message&#8217;</p>
<p>盡量可以的指明異常名，如：</p>
<pre class="brush: python; title: ; notranslate">
try:
    import platform_specific_module
except ImportError:
    platform_specific_module = None
</pre>
<p>避免使用無異常名的 except: 語句，它會捕獲全部的異常（如 Ctrl C）。<br />
將異常綁定到名字的方法：</p>
<pre class="brush: python; title: ; notranslate">
try:
    process_data()
except Exception as exc:
    raise DataProcessingFailedError(str(exc))
</pre>
<p>try: 中的語句要盡量減少，如：<br />
# 正確的寫法：</p>
<pre class="brush: python; title: ; notranslate">
try:
    value = collection[key]
except KeyError:
    return key_not_found(key)
else:
    return handle_value(value)
</pre>
<p># 錯誤的寫法</p>
<pre class="brush: python; title: ; notranslate">
try:
    # Too broad!
    return handle_value(collection[key])
except KeyError:
    # Will also catch KeyError raised by handle_value()
    return key_not_found(key)
</pre>
<p>如果資源只適用於某個代碼段內，使用 with 或 try/finally 來確保能進行清理工作<br />
上下文管理器應用通過一個單獨的函數或方法來呼叫，如：<br />
# 正確的做法：</p>
<pre class="brush: python; title: ; notranslate">
with conn.begin_transaction():
    do_stuff_in_transaction(conn)
</pre>
<p># 錯誤的做法：</p>
<pre class="brush: python; title: ; notranslate">
with conn:
    do_stuff_in_transaction(conn)
</pre>
<p>return 語句應該一致，如：<br />
# 正確的做法：</p>
<pre class="brush: python; title: ; notranslate">
def foo(x):
    if x &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; 0:
        return None
    return math.sqrt(x)
</pre>
<p># 錯誤的做法：</p>
<pre class="brush: python; title: ; notranslate">
def foo(x):
    if x &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;= 0:
        return math.sqrt(x)

def bar(x):
    if x &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; 0:
        return
    return math.sqrt(x)
</pre>
<p><strong>使用字符串的方法，而不是用 string 模組中的方法</strong><br />
使用 &#8220;.startswith() 和 &#8220;.endswidth() 而不用 slicing 來檢查前綴和後綴：<br />
# 正確：<br />
if foo.startswith(&#8216;bar&#8217;):<br />
# 錯誤：<br />
if foo[:3] == &#8216;bar&#8217;:<br />
<strong>判斷對象的類型用 isinstance 而不直接 type 比較，如：</strong><br />
# 正確：<br />
if isinstance(obj, int):<br />
# 錯誤:<br />
if type(obj) is type(1):<br />
<strong>對序列是否空的判斷不用 len，如：</strong><br />
# 正確：<br />
if not seq:<br />
if seq:<br />
# 錯誤：<br />
if len(seq):<br />
if not len(seq):<br />
<strong>布林值的比較：</strong><br />
# 正確：<br />
if greeting:<br />
# 不要這樣:<br />
if greeting == True:<br />
# 這樣更不行：<br />
if greeting is True:</p>
<hr />
<p>參考資料：</p>
<p><a href="https://www.python.org/dev/peps/pep-0008/">PEP 8 &#8212; Style Guide for Python Code</a></p>
<p>這篇文章 <a rel="nofollow" href="http://cflin.com/wordpress/603/pep8-python%e7%b7%a8%e7%a2%bc%e8%a6%8f%e7%af%84%e6%89%8b%e5%86%8a">PEP8 Python 編碼規範手冊</a> 最早出現於 <a rel="nofollow" href="http://cflin.com/wordpress">台大系統訓練班課程網頁 (林奇賦)</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>http://cflin.com/wordpress/603/pep8-python%e7%b7%a8%e7%a2%bc%e8%a6%8f%e7%af%84%e6%89%8b%e5%86%8a/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
