Python Constants
In this page:
CONSTANT_NAME = value # UPPER_CASE by convention
वैचारिक Constants
Python में कोई समर्पित const keyword नहीं है — परंपरा के अनुसार, developers किसी variable को ALL_CAPS में नाम देते हैं (जैसे MAX_RETRIES) ताकि दूसरे पाठकों को संकेत मिले कि "इस value को बदलना नहीं है," भले ही interpreter खुद आपको इसे दोबारा assign करने से न रोके।
उदाहरण: Conceptual Constants
MAX_RETRIES = 5
print(MAX_RETRIES)
MAX_RETRIES = 10 # interpreter allows this even though the name signals "don't change me"
print(MAX_RETRIES)
Constant Modules
संबंधित constants को config.py जैसे अलग module में समूहित करना और जहाँ ज़रूरत हो वहाँ import करना, सेटिंग्स को एक ही जगह केंद्रित रखता है, इसलिए API URL जैसी value बदलने का मतलब पूरे codebase में खोजने की बजाय एक line edit करना होता है।
उदाहरण: Constant Modules
# config.py would hold:
# API_URL = "https://api.example.com"
# Importing it elsewhere: from config import API_URL
API_URL = "https://api.example.com"
print(API_URL)
Numeric Constants
बार-बार आने वाले संख्यात्मक literal को नाम देना — जैसे अपने code में जगह-जगह बिखरे 100 की जगह MAX_USERS = 100 — बिना समझाई "magic number" को खुद-समझाने वाला नाम बना देता है और भविष्य के बदलाव को एक line का edit बना देता है।
उदाहरण: Numeric Constants
MAX_USERS = 100
print(f"Server allows up to {MAX_USERS} users")
String Constants
error messages, status labels या welcome banner जैसे निश्चित text values नामित string constants के अच्छे उम्मीदवार हैं, क्योंकि एक ही string को कई जगह hardcode करने पर खतरा रहता है कि एक को edit करने और बाकियों को न करने पर प्रतियाँ आपस में मेल खोने लगें।
उदाहरण: String Constants
ERROR_NOT_FOUND = "Resource not found"
print(ERROR_NOT_FOUND)
Constants के सर्वोत्तम तरीके
सभी constant परिभाषाओं को file के ऊपर, बाकी logic से पहले रखना उन्हें ढूँढना और बदलना आसान बनाता है, असंबंधित code में scroll किए बिना — एक छोटी परंपरा जिसका फ़ायदा उसी क्षण मिलता है जब किसी और को file maintain करनी पड़े।
उदाहरण: Best Practices for Constants
MAX_RETRIES = 3 # constants defined near the top of the file
TIMEOUT_SECONDS = 30
def connect():
print("Connecting with timeout", TIMEOUT_SECONDS)
connect()
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: