Python PEP 8 स्टाइल गाइड
In this page:
PEP 8 क्या है?
PEP 8, Python की official style guide है, और इसे फॉलो करना सिर्फ नियमों का पालन करने के लिए नहीं है -- यह इसलिए है ताकि कोई भी Python developer अनजान code को उस particular author की personal formatting habits सीखे बिना पढ़ सके।
उदाहरण: What is PEP 8?
# PEP 8 is Python's official style guide
def calculate_total(price, quantity):
return price * quantity
print(calculate_total(10, 3))
Naming Conventions
PEP 8, variables और functions के लिए snake_case, class names के लिए PascalCase, और constants के लिए UPPER_SNAKE_CASE इस्तेमाल करने की सलाह देता है।
Consistent naming से reader सिर्फ यह देखकर कि identifier कैसे capitalize किया गया है, उसकी definition पढ़ने से पहले ही अंदाज़ा लगा सकता है कि वह किस तरह की चीज़ को refer कर रहा है।
उदाहरण: Naming Conventions
user_count = 5 # snake_case for variables
MAX_RETRIES = 3 # UPPER_SNAKE_CASE for constants
class UserAccount: # PascalCase for classes
pass
print(user_count, MAX_RETRIES)
Whitespace और Spacing
PEP 8, brackets या parentheses के अंदर सीधे extra whitespace (foo( x ) की जगह foo(x)) और commas या colons से ठीक पहले whitespace डालने को हतोत्साहित करता है, क्योंकि inconsistent spacing से code बिना किसी असली clarity के ज़्यादा noisy दिखने लगता है।
उदाहरण: Whitespace and Spacing
def foo(x):
return x
print(foo(5)) # no extra space inside parentheses
Blank Lines
Top-level function और class definitions बिल्कुल दो blank lines से अलग होने चाहिए, जबकि किसी class के अंदर के methods एक blank line से अलग किए जाते हैं।
यह consistent vertical spacing reader की आँख को जल्दी पहचानने में मदद करती है कि एक definition कहाँ खत्म होती है और अगली कहाँ से शुरू होती है।
उदाहरण: Blank Lines
def first_function():
pass
def second_function():
pass # two blank lines above separate the top-level functions
print("Two blank lines separate top-level functions")
Imports के साथ Style
Imports किसी file के बिल्कुल ऊपर होने चाहिए, एक specific order में group किए हुए: पहले standard library imports, फिर third-party packages, फिर आपके अपने local modules -- हर group के बीच एक blank line के साथ।
यह ordering किसी file की external dependencies को एक नज़र में स्पष्ट कर देती है।
उदाहरण: Style with Imports
import math # standard library
# import requests # third-party would go next
print(math.pi)
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects