forked from blshaer/python-by-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_pep8.py
More file actions
334 lines (258 loc) · 8.48 KB
/
01_pep8.py
File metadata and controls
334 lines (258 loc) · 8.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
"""
================================================================================
File: 01_pep8.py
Topic: PEP 8 - Python Style Guide
================================================================================
This file demonstrates PEP 8, the official Python style guide. Following PEP 8
makes your code more readable, consistent, and professional. These are
conventions, not strict rules, but following them is highly recommended.
Key Concepts:
- Indentation and whitespace
- Naming conventions
- Line length and wrapping
- Imports organization
- Comments and docstrings
Reference: https://peps.python.org/pep-0008/
================================================================================
"""
# =============================================================================
# 1. INDENTATION
# =============================================================================
# Use 4 spaces per indentation level. Never mix tabs and spaces.
# GOOD
def function_with_proper_indentation():
if True:
for i in range(10):
print(i)
# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Hanging indent (add a level)
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# =============================================================================
# 2. LINE LENGTH
# =============================================================================
# Limit lines to 79 characters (72 for docstrings/comments)
# GOOD - Use implicit line continuation
total = (first_variable
+ second_variable
+ third_variable)
# GOOD - Use backslash when necessary
with open('/very/long/path/to/file.txt') as file_one, \
open('/another/long/path/to/file.txt') as file_two:
pass
# =============================================================================
# 3. BLANK LINES
# =============================================================================
# - 2 blank lines around top-level functions and classes
# - 1 blank line between methods in a class
class FirstClass:
"""First class."""
pass
class SecondClass:
"""Second class."""
def method_one(self):
"""First method."""
pass
def method_two(self):
"""Second method."""
pass
def top_level_function():
"""A top-level function."""
pass
# =============================================================================
# 4. IMPORTS
# =============================================================================
# - One import per line
# - Group in order: standard library, third-party, local
# - Use absolute imports
# GOOD
import os
import sys
from typing import List, Optional
# Third party imports (after blank line)
# import numpy as np
# import pandas as pd
# Local imports (after blank line)
# from mypackage import mymodule
# BAD - Multiple imports on one line
# import os, sys
# =============================================================================
# 5. WHITESPACE
# =============================================================================
# GOOD - No extra whitespace inside brackets
spam = [1, 2, 3]
ham = {"key": "value"}
eggs = (1,)
# BAD
# spam = [ 1, 2, 3 ]
# ham = { 'key': 'value' }
# GOOD - One space around operators
x = 1
y = 2
z = x + y
# BAD - No space around = in keyword arguments
# def function(x, y = 5):
def function(x, y=5):
pass
# GOOD - Space after comma
some_list = [1, 2, 3]
# GOOD - No space before colon in slices
some_list[1:3]
some_list[::2]
# =============================================================================
# 6. NAMING CONVENTIONS
# =============================================================================
# Variables and functions: lowercase_with_underscores (snake_case)
user_name = "John"
total_count = 42
def calculate_average(numbers):
return sum(numbers) / len(numbers)
# Constants: UPPERCASE_WITH_UNDERSCORES
MAX_BUFFER_SIZE = 4096
DEFAULT_TIMEOUT = 30
PI = 3.14159
# Classes: CapitalizedWords (PascalCase)
class UserAccount:
pass
class HttpConnection:
pass
# Private: prefix with underscore
_internal_variable = "private"
def _internal_function():
pass
class MyClass:
def _protected_method(self):
"""Single underscore = protected (convention)."""
pass
def __private_method(self):
"""Double underscore = name mangling (truly private)."""
pass
# =============================================================================
# 7. COMMENTS
# =============================================================================
# GOOD - Inline comments have at least 2 spaces before #
x = 5 # This is an inline comment
# Block comments precede the code they describe
# This is a block comment that explains
# the following piece of code.
complex_calculation = 1 + 2 + 3
# Don't state the obvious
# BAD: x = 5 # Assign 5 to x
# GOOD: x = 5 # Default timeout in seconds
# =============================================================================
# 8. DOCSTRINGS
# =============================================================================
def example_function(param1, param2):
"""
Brief description of the function.
Longer description if needed. Explain what the function
does, not how it does it.
Args:
param1: Description of first parameter
param2: Description of second parameter
Returns:
Description of what is returned
Raises:
ValueError: When param1 is negative
Example:
>>> example_function(1, 2)
3
"""
return param1 + param2
class ExampleClass:
"""Brief description of the class.
Longer description of the class including its purpose
and usage patterns.
Attributes:
attr1: Description of first attribute
attr2: Description of second attribute
"""
def __init__(self, attr1, attr2):
"""Initialize ExampleClass."""
self.attr1 = attr1
self.attr2 = attr2
# =============================================================================
# 9. COMPARISON AND BOOLEAN
# =============================================================================
# Use 'is' and 'is not' for None comparisons
# GOOD
x = None
if x is None:
pass
# BAD
# if x == None:
# Use 'is not' instead of 'not ... is'
# GOOD
if x is not None:
pass
# BAD
# if not x is None:
# Don't compare boolean values with == or !=
# GOOD
flag = True
if flag:
pass
# BAD
# if flag == True:
# if flag is True: # Only use when testing identity
# =============================================================================
# 10. EXCEPTION HANDLING
# =============================================================================
# Catch specific exceptions
# GOOD
try:
value = int(user_input)
except ValueError:
print("Invalid input")
# BAD - Too broad
# try:
# value = int(user_input)
# except: # or except Exception:
# print("Error")
# Use 'raise' to re-raise exception
try:
process_data()
except ValueError:
logger.error("Bad value")
raise
# =============================================================================
# 11. FUNCTION ANNOTATIONS (Type Hints)
# =============================================================================
def greeting(name: str) -> str:
"""Return a greeting."""
return f"Hello, {name}!"
# Complex types
from typing import List, Dict, Optional
def process_items(
items: List[str],
config: Dict[str, int],
default: Optional[str] = None
) -> bool:
"""Process items with configuration."""
return True
# =============================================================================
# 12. SUMMARY: KEY RULES
# =============================================================================
print("PEP 8 Summary - Key Rules:")
print("""
1. Use 4 spaces for indentation
2. Limit lines to 79 characters
3. Use blank lines to separate functions and classes
4. Organize imports: standard lib, third-party, local
5. Use snake_case for functions and variables
6. Use PascalCase for classes
7. Use UPPER_CASE for constants
8. Use spaces around operators and after commas
9. Write docstrings for all public modules, functions, classes
10. Compare with 'is' for None, use bool directly
""")
# Use flake8 or black to automatically check/format code
print("Tools to help with PEP 8:")
print(" - flake8: Check for PEP 8 violations")
print(" - black: Automatic code formatting")
print(" - isort: Sort imports automatically")
print(" - pylint: Comprehensive code analysis")