はじめに
この実験(Lab)では、Python コードに PEP 8 スタイルガイドを適用する方法を学びます。PEP 8 は Python の公式スタイルガイドであり、読みやすく一貫性のあるコードを書くための推奨事項のセットを提供します。これらのガイドラインに従うことで、自分自身や他の人がコードを読みやすくなります。
インデント、行の長さ、スペース、命名規則など、主要な PEP 8 ルールを実装する練習をします。また、autopep8ツールを使用してコードを自動的にフォーマットする方法を学び、時間を節約し、コミュニティ標準への準拠を保証する方法も習得します。
PEP 8 のインデントと行の長さを理解する
適切なインデントと行の長さは、読みやすい Python コードの基本です。このステップでは、これら 2 つの側面に関する PEP 8 ガイドラインを学習し、適用します。
インデント: PEP 8 では、インデントレベルごとに 4 つのスペースを使用することが推奨されています。これは Python コミュニティにおける強力な慣習です。
行の長さ: PEP 8 では、すべての行を最大 79 文字に制限することを推奨しています。Docstring およびコメントについては、制限は 72 文字です。これにより、特に小さな画面やコードを並べて比較する場合に、可読性が向上します。
これを実践してみましょう。左側のファイルエクスプローラーで、ファイル indentation_example.py を見つけて開いてください。内部のコードは、関数定義と複数行ステートメントの正しいインデントを示しています。
## Correct indentation using 4 spaces.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
## Define some variables for demonstration.
var_one = "first"
var_two = "second"
var_three = "third"
var_four = "fourth"
## Aligning with the opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
## Using a hanging indent. The first line has no arguments,
## and subsequent lines are indented to distinguish them.
bar = long_function_name(
var_one, var_two,
var_three, var_four)
## A multi-line list.
my_list = [
1, 2, 3,
4, 5, 6,
]
## Calling the functions to produce output.
long_function_name("first call", "second", "third", "fourth")
foo = long_function_name("second call", "second", "third", "fourth")
bar = long_function_name("third call", "second", "third", "fourth")
コードを確認した後、スクリプトを実行してその出力を確認します。WebIDE の下部にあるターミナルを開き、次のコマンドを実行します。
python ~/project/indentation_example.py
スクリプトが実行され、各関数呼び出しの最初の引数が出力されます。出力は次のようになります。
first call
second call
third call
この演習は、一貫したインデントが複雑な関数呼び出しやデータ構造をいかに読みやすくするかを示しています。
スペーシングと命名規則を実践する
Consistent spacing and clear naming conventions are also crucial for code readability. This step covers the PEP 8 rules for both.
Spacing:
- Use a single space around most operators (
=,+=,==,<,>). - Use a space after commas in lists, tuples, and function arguments.
- Avoid extra spaces immediately inside parentheses, brackets, or braces.
Naming Conventions:
snake_case: Use for functions and variables (e.g.,my_function,user_name).PascalCase: Use for class names (e.g.,MyClass).UPPERCASE_SNAKE_CASE: Use for constants (e.g.,MAX_CONNECTIONS).
Let's see these rules in action. In the file explorer, open the style_guide_example.py file. The code includes examples of correct spacing and naming, with commented-out incorrect versions for comparison.
## A constant
MAX_OVERFLOW = 100
## A class name in PascalCase
class MySampleClass:
def __init__(self, name):
## A variable name in snake_case
self.instance_name = name
## A function name in snake_case
def sample_method(self, var_one, var_two):
## Correct spacing around operators and after comma
result = var_one + var_two
print(self.instance_name, result)
## --- Incorrect examples for comparison ---
## class mySampleClass:
## def SampleMethod(self, varOne, varTwo):
## result=varOne+varTwo
## print(self.instance_name,result)
## Create an object and call the method
my_object = MySampleClass("TestObject")
my_object.sample_method(10, 5)
Save the file if you made any changes, and run it from the terminal:
python ~/project/style_guide_example.py
The output will show the name of the object and the result of the calculation:
TestObject 15
By following these spacing and naming rules, you make the structure and purpose of your code immediately clearer to any reader.
自動フォーマットに autopep8 を使用する
一貫したスペーシングと明確な命名規則も、コードの可読性にとって非常に重要です。このステップでは、その両方に関する PEP 8 のルールを取り上げます。
スペーシング:
- ほとんどの演算子(
=,+=,==,<,>)の周りには、スペースを 1 つ使用します。 - リスト、タプル、関数の引数では、コンマの後にスペースを使用します。
- 丸括弧、角括弧、波括弧のすぐ内側にある余分なスペースは避けます。
命名規則:
snake_case: 関数と変数に使用します(例:my_function,user_name)。PascalCase: クラス名に使用します(例:MyClass)。UPPERCASE_SNAKE_CASE: 定数に使用します(例:MAX_CONNECTIONS)。
これらのルールがどのように機能するかを見てみましょう。ファイルエクスプローラーで、style_guide_example.pyファイルを開いてください。このコードには、比較のためにコメントアウトされた誤ったバージョンと共に、正しいスペーシングと命名の例が含まれています。
## A constant
MAX_OVERFLOW = 100
## A class name in PascalCase
class MySampleClass:
def __init__(self, name):
## A variable name in snake_case
self.instance_name = name
## A function name in snake_case
def sample_method(self, var_one, var_two):
## Correct spacing around operators and after comma
result = var_one + var_two
print(self.instance_name, result)
## --- Incorrect examples for comparison ---
## class mySampleClass:
## def SampleMethod(self, varOne, varTwo):
## result=varOne+varTwo
## print(self.instance_name,result)
## Create an object and call the method
my_object = MySampleClass("TestObject")
my_object.sample_method(10, 5)
変更を加えた場合はファイルを保存し、ターミナルから実行します。
python ~/project/style_guide_example.py
出力には、オブジェクトの名前と計算結果が表示されます。
TestObject 15
これらのスペーシングと命名のルールに従うことで、コードの構造と目的が、それを読むすべての人にとって即座に明確になります。
統合:スクリプトのリファクタリング
いよいよ、学んだことすべてを適用する時が来ました。このステップでは、PEP 8 のガイドラインに違反しているスクリプトを手動でリファクタリングします。この演習は、インデント、スペーシング、命名規則に対する理解度を試すものです。
まず、ファイルエクスプローラーからrefactor_challenge.pyを開いてください。これには、長方形の面積を計算しますが、スタイルが不十分な次のコードが含まれています。
## This script calculates the area of a rectangle and prints it.
def CalculateArea(width,height):
Area = width*height ## calculate area
return Area
w = 10
h = 5
rectangle_area=CalculateArea(w,h)
print("The area of the rectangle is:",rectangle_area)
あなたのタスクは、このコードをエディタで手動で編集し、PEP 8 に準拠させることです。以下の点に注意して修正してください。
- 関数名: 関数名は
snake_caseである必要があります。 - 変数名: 変数名も
snake_caseである必要があります。 - スペーシング: 演算子の周りやコンマの後に適切なスペースがあるか確認します。
- コメント: インラインコメントでは、
#の後にスペースが必要です。
ご自身でコードをリファクタリングする時間を取ってください。完了したら、コードは次のようになっているはずです。
## This script calculates the area of a rectangle and prints it.
def calculate_area(width, height):
"""Calculate and return the area of a rectangle."""
area = width * height ## calculate area
return area
w = 10
h = 5
rectangle_area = calculate_area(w, h)
print("The area of the rectangle is:", rectangle_area)
変更点に注目してください:CalculateAreaがcalculate_areaに、Areaがareaになり、スペーシングが修正されました。また、関数の動作を説明するために、ベストプラクティスである docstring(ドキュメンテーション文字列)を関数に追加しました。
変更を保存し、スクリプトを実行して、まだ正しく動作することを確認します。
python ~/project/refactor_challenge.py
出力は次のようになるはずです。
The area of the rectangle is: 50
この演習は、スタイルのためのリファクタリングがコードの動作を変更するわけではないが、可読性と保守性を劇的に向上させることを示しています。
まとめ
この「実験」(Lab)では、Python の PEP 8 スタイルガイドの基本を学びました。インデント、行の長さ、スペーシング、命名規則のルールを適用する練習をしました。また、コードを自動的にフォーマットしてこれらの標準を満たすためのautopep8の強力さも発見しました。最後のリファクタリング「チャレンジ」を完了することで、これらの概念をすべて統合し、スタイルが不十分なスクリプトをクリーンで読みやすく、保守性の高い Python コードに変えました。PEP 8 を遵守することは、コラボレーションを促進しコード品質を向上させるため、すべてのプロフェッショナルな Python 開発者にとって重要な実践です。



