Python Class Constants: 6 Practical Tips for More Elegant Code

In a million-dollar bug incident last year during a promotional event on an e-commerce platform, a new user coupon value unexpectedly changed from 50 yuan to 500 yuan, resulting in losses exceeding one million within two hours. After investigation, it was found that a developer mistakenly changed <span>COUPON_VALUE = 50</span> to 500 while modifying the configuration. If class constants and naming conventions had been used, this error could have been avoided…

This illustrates the power of class constants—today, we will teach you how to effectively utilize this often-overlooked feature of Python through real-world examples.

1. Three Core Values of Class Constants

1. Tamper-Proof Protection Pain point scenario: Key configuration values are accidentally modified during collaborative work.

Solution:

class PaymentConfig:
    # Financial-grade precision requirements
    USD_EXCHANGE_RATE = 6.8912  # Exchange rate
    TRANSACTION_FEE_RATE = 0.003  # Transaction fee rate
    
    @classmethod
    def get_fee(cls, amount):
        return amount * cls.TRANSACTION_FEE_RATE

Meituan Technical Team Practice: Centralized management of payment-related constants, changes require an approval process.

2. Configuration Management Center Real-world case: A/B testing configuration for a short video app.

class ExperimentConfig:
    # Current experiment version
    VIDEO_QUALITY_LEVEL = "1080P"  # Video quality level
    MAX_CACHE_SIZE = 1024  # Unit MB
    
    @classmethod
    def should_enable_new_feature(cls):
        return datetime.now() > datetime(2023,11,1)

ByteDance Experience: Implementing feature toggles through class constants, allowing hot updates without restarting services.

3. Documentation Auto-Generator Advanced usage: Let constants speak for themselves.

class ErrorCodes:
    """API error code system"""
    SUCCESS = (0, "Operation successful")
    INVALID_TOKEN = (1001, "Invalid token")
    PERMISSION_DENIED = (1002, "Insufficient permissions")
    
    @classmethod
    def get_message(cls, code):
        return next(v[1] for v in vars(cls).values() if v[0] == code)

Alibaba Development Standards: Centralized maintenance of error codes, combined with automated documentation generation.

2. Three Advanced Techniques Known Only to Senior Engineers

1. Constant Inheritance Black Technology Scenario: Building a multi-country payment system.

class BasePayment:
    CURRENCY = "USD"
    MIN_AMOUNT = 1.0

class CNPayment(BasePayment):
    CURRENCY = "CNY"          # Override parent class constant
    MIN_AMOUNT = 10.0         # Minimum 10 yuan in RMB
    FESTIVAL_BONUS = 5.0      # China-specific constant

PayPal Development Experience: Achieving multi-currency configuration through inheritance.

2. Constant Automated Validation Defensive programming example:

class SecurityConfig:
    JWT_SECRET = os.getenv("JWT_SECRET")
    TOKEN_EXPIRE = 3600  # Unit seconds
    
    def __init__(self):
        if not self.JWT_SECRET:
            raise ValueError("JWT secret not configured!")
        if self.TOKEN_EXPIRE > 86400*7:
            raise SecurityException("Session validity period too long")

Essential for financial systems: Automatically validate key configurations at startup.

3. Constant Versioning Gradual release plan:

class FeatureFlags:
    # Feature toggle version control
    NEW_CHECKOUT_V1 = False  # Old checkout
    NEW_CHECKOUT_V2 = True   # New checkout
    
    @classmethod
    def enable_v2_for_user(cls, user_id):
        return user_id % 10 == 0  # 10% of users in gradual release

JD 618 Practical Experience: Achieving progressive release through constant combinations.

3. Learning Design Patterns from Open Source Projects

1. The Secret of Django’s settings.py Upon reviewing the Django source code:

class Settings:
    DEBUG = False
    ALLOWED_HOSTS = []
    DATABASES = {}
    
    def __init__(self, settings_module):
        # Load configuration through class constants + environment variables
        self.SETTINGS_MODULE = settings_module
        mod = importlib.import_module(self.SETTINGS_MODULE)
        for setting in dir(mod):
            if setting.isupper():
                setattr(self, setting, getattr(mod, setting))

Learning Point: Use constants as configuration entry points to support dynamic loading.

2. HTTP Status Codes in the Requests Library Source code snippet appreciation:

class HTTPStatus:
    # Elegant status code definitions
    OK = 200
    CREATED = 201
    BAD_REQUEST = 400
    NOT_FOUND = 404
    
    @classmethod
    def is_success(cls, code):
        return 200 <= code < 300

Worth learning: Combining constants with business logic.

4. Pitfall Guide: 5 Common Mistakes with Constants

1. The Trap of Over-Constantization Defining <span>user.name</span> as a constant? NO! Constants should only be used for truly unchanging values.

2. Cross-Module Reference Disasters

# Incorrect example
from config import MAX_RETRIES
class A:
    MAX = MAX_RETRIES  # Loses constant characteristics

Correct Approach: Always access through the original class name.

3. Thread Safety Misconceptions Modifying class constants in a multi-threaded environment? Python allows it, but it is absolutely prohibited!

4. Configuration File Confusion

Confusing frequently modified configurations as constants should be avoided:

• Class constants: Fixed values at the code level

• Environment variables: Deployment-level configurations

• Database configurations: Runtime variable parameters

5. Documentation Deficiency Syndrome

Good constants are documentation in themselves:

class Physics:
    SPEED_OF_LIGHT = 299792458  # Unit m/s
    GRAVITATIONAL_CONSTANT = 6.67430e-11  # Unit m³·kg⁻¹·s⁻²

5. Future Trends: When Constants Meet AI

Google’s latest research shows that code using standardized constants:

• Has a 73% higher probability of being correctly completed by Copilot.

• Code review pass rates increase by 58%.

• Module reuse rates increase by 42%.

Prediction: In the era of AI programming, the standardized use of constants will become a key differentiator between ordinary developers and architects.

Practical Exercise Identify three magic numbers in your current project and try to refactor them using class constants to experience the following changes:

  1. Improvement in code readability
  2. Convenience of functionality modification
  3. Communication costs in team collaboration

Feel free to share your refactoring cases in the comments!

Leave a Comment