How to overload python ternary operator?

The ternary operator in Python (value_if_true if condition else value_if_false) cannot be directly overloaded like other operators. However, you can create reusable ternary-like functionality using lambdas, functions, or custom classes.

Using Lambda Functions

You can wrap ternary logic in a lambda function to make it reusable ?

# Create a reusable ternary function
result = lambda x: 1 if x < 3 else 10

print(result(2))
print(result(1000))
1
10

Using Regular Functions

For more complex logic, regular functions provide better readability ?

def categorize_number(x):
    return "small" if x < 10 else "large"

def grade_score(score):
    return "Pass" if score >= 60 else "Fail"

print(categorize_number(5))
print(categorize_number(15))
print(grade_score(75))
print(grade_score(45))
small
large
Pass
Fail

Creating a Custom Ternary Class

You can create a class that mimics ternary operator behavior ?

class TernaryOperator:
    def __init__(self, condition_func, true_value, false_value):
        self.condition = condition_func
        self.true_val = true_value
        self.false_val = false_value
    
    def evaluate(self, x):
        return self.true_val if self.condition(x) else self.false_val

# Create instances
is_even = TernaryOperator(lambda x: x % 2 == 0, "Even", "Odd")
size_check = TernaryOperator(lambda x: x > 100, "Big", "Small")

print(is_even.evaluate(4))
print(is_even.evaluate(7))
print(size_check.evaluate(150))
print(size_check.evaluate(50))
Even
Odd
Big
Small

Comparison

Method Best For Readability
Lambda Simple, one-line conditions Good for short logic
Function Complex logic, reusability Excellent
Custom Class Advanced patterns, state Good for complex cases

Conclusion

While Python's ternary operator cannot be overloaded directly, you can create reusable ternary-like functionality using lambdas, functions, or custom classes. Choose functions for complex logic and lambdas for simple conditions.

Updated on: 2026-03-24T20:35:52+05:30

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements