From 9476aafb5b9d029660af78f49c2e6bc44a5a3144 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Thu, 14 Aug 2025 14:43:52 -0400 Subject: [PATCH 1/3] Term entry for total_ordering class decorator under the functools module. Also, recommending adding Python to Subjects and Class Decorator to tags. --- .../terms/total-ordering/total-ordering.md | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 content/python/concepts/functools-module/terms/total-ordering/total-ordering.md diff --git a/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md b/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md new file mode 100644 index 00000000000..4789144b1b8 --- /dev/null +++ b/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md @@ -0,0 +1,134 @@ +--- +Title: total_ordering() +Description: This term entry explains total_ordering(), which is a class decorator under the functools module. +Subjects: Python +Tags: Class Decorator +Catalog Content: content/python/concepts/functools-module/terms/total-ordering/total-ordering.md +--- + +The **`total_ordering()`** class decorator under the `functools` module modifies a class by defining any missing rich comparison methods. + +There are six rich comparison methods that define and customize operator behavior within a class: + +```codebyte/python +#This is the rich comparison method that defines and customizes the '==' operator (Equal To) within a class. +def __eq__(self, other) + +#This is the rich comparison method that defines and customizes the '!=' operator (Not Equal To) within a class. +def __ne__(self, other) + +#This is the rich comparison method that defines and customizes the '<' operator (Less Than) within a class. +def __lt__(self, other) + +#This is the rich comparison method that defines and customizes the '<=' operator (Less Than or Equal To) within a class. +def __le__(self, other) + +#This is the rich comparison method that defines and customizes the '>' operator (Greater Than) within a class. +def __gt__(self, other) + +#This is the rich comparison method that defines and customizes the '>=' operator (Greater Than or Equal To) within a class. +def __ge__(self, other) +``` + +Instead of defining all six rich comparison methods, the **`total_ordering()`** class decorator only requires two rich comparison methods, `__eq__` and any other rich comparison method. The benefit is coding efficiency. + +**Requirements:** + - `def __eq__(self, other)` must be defined. + - At least one other rich comparison method must be defined. + +**Characteristics:** +- **Wrapping**: Syntax `@functools.total_ordering` or `@total_ordering` wraps the next class defined. No need to call manually. +- **Order**: Requirements themselves do not need to be ordered within the class definition, e.g. `def __eq__(self, other)` could come after `def __lt__(self, other)`. +- **Returns**: Returns `True` or `False` boolean when called and printed. +- **Performance**: Performance may be negatively impacted if decorators are called frequently. + +## Syntax +There are two approaches to `total_ordering` syntax: + +**Option 1 - Wrap** +```codebyte/python +from functools import total_ordering + +@total_ordering +class Name: + def __init__(self, first_comparison): + self.first_comparison = first_comparison + + def __eq__(self, other): + return self.first_comparison == other.first_comparison + + def __lt__(self, other): + return self.first_comparison < other.first_comparison +``` +**Option 2 - Call** +```codebyte/python +from functools import total_ordering + +class Name: + def __init__(self, first_comparison): + self.first_comparison = first_comparison + + def __eq__(self, other): + return self.first_comparison == other.first_comparison + + def __lt__(self, other): + return self.first_comparison < other.first_comparison + +name = total_ordering(Name) +``` + +## Example +This example demonstrates that `total_ordering` defines missing rich comparison methods within a class. +```codebyte/python +from functools import total_ordering + +@total_ordering +class Age: + def __init__(self, age_number): + self.age_number = age_number + + def __eq__(self, other): + return self.age_number == other.age_number + + def __lt__(self, other): + return self.age_number < other.age_number + +#The __gt__ method (greater than) was not defined explicitly in the code above. That's where total_ordering can help! +print(Age(20) > Age(60)) +``` +Here is the output: +``` +False +``` +This example demonstrates the customization capabilities when using rich comparison methods and total_ordering. +```codebyte/python +from functools import total_ordering + +@total_ordering +class Sky_Color: + def __init__(self, color): + self.color = color + +#The __eq__ method (equal to) is customized and defined as 'not equal to blue' within this class. Any class object that is not equal to blue will return a True boolean. + def __eq__(self, other): + return self.color != "blue" + + def __lt__(self, other): + return self.color < other.color + +blue_color = "blue" +print(f"Is the sky {blue_color}?") +print(f"{blue_color == Sky_Color(blue_color)}") + +#The class Sky_Color does not explicitly define the '!=' operator (Not Equal To). This is automically defined by the use of total_ordering. +print(f"\nIs the sky never {blue_color}?") +print(f"{blue_color != Sky_Color(blue_color)}") +``` +This will print: +``` +Is the sky blue? +False + +Is the sky never blue? +True +``` From c3da8d9f50936eb46faec417fd4c7354e8975104 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Tue, 4 Nov 2025 12:08:08 +0530 Subject: [PATCH 2/3] content fixes --- .../terms/total-ordering/total-ordering.md | 187 +++++++++--------- 1 file changed, 92 insertions(+), 95 deletions(-) diff --git a/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md b/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md index 4789144b1b8..604512b485b 100644 --- a/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md +++ b/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md @@ -1,134 +1,131 @@ --- -Title: total_ordering() -Description: This term entry explains total_ordering(), which is a class decorator under the functools module. -Subjects: Python -Tags: Class Decorator -Catalog Content: content/python/concepts/functools-module/terms/total-ordering/total-ordering.md +Title: 'total_ordering()' +Description: 'Generates missing comparison methods in a class based on a minimal set of defined ones.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Classes' + - 'Modules' + - 'Python' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' --- -The **`total_ordering()`** class decorator under the `functools` module modifies a class by defining any missing rich comparison methods. +The **`total_ordering()`** decorator from the functools module simplifies the creation of fully ordered classes. By defining the `__eq__()` method and one additional comparison method (`__lt__()`, `__le__()`, `__gt__()`, or `__ge__()`), all other rich comparison methods are automatically generated. -There are six rich comparison methods that define and customize operator behavior within a class: +This decorator reduces redundant code in custom classes that require complete ordering behavior for comparisons, sorting, and equality checks. -```codebyte/python -#This is the rich comparison method that defines and customizes the '==' operator (Equal To) within a class. -def __eq__(self, other) - -#This is the rich comparison method that defines and customizes the '!=' operator (Not Equal To) within a class. -def __ne__(self, other) +## Syntax -#This is the rich comparison method that defines and customizes the '<' operator (Less Than) within a class. -def __lt__(self, other) +```pseudo +from functools import total_ordering -#This is the rich comparison method that defines and customizes the '<=' operator (Less Than or Equal To) within a class. -def __le__(self, other) +@total_ordering +class ClassName: + def __eq__(self, other): ... + def __lt__(self, other): ... +``` -#This is the rich comparison method that defines and customizes the '>' operator (Greater Than) within a class. -def __gt__(self, other) +**Parameters:** -#This is the rich comparison method that defines and customizes the '>=' operator (Greater Than or Equal To) within a class. -def __ge__(self, other) -``` +The `total_ordering()` decorator takes no parameters. -Instead of defining all six rich comparison methods, the **`total_ordering()`** class decorator only requires two rich comparison methods, `__eq__` and any other rich comparison method. The benefit is coding efficiency. +**Return value:** -**Requirements:** - - `def __eq__(self, other)` must be defined. - - At least one other rich comparison method must be defined. +Returns a class with the missing comparison methods (`__le__`, `__gt__`, and `__ge__`) automatically added. -**Characteristics:** -- **Wrapping**: Syntax `@functools.total_ordering` or `@total_ordering` wraps the next class defined. No need to call manually. -- **Order**: Requirements themselves do not need to be ordered within the class definition, e.g. `def __eq__(self, other)` could come after `def __lt__(self, other)`. -- **Returns**: Returns `True` or `False` boolean when called and printed. -- **Performance**: Performance may be negatively impacted if decorators are called frequently. +## Example 1: Numeric Wrapper Class -## Syntax -There are two approaches to `total_ordering` syntax: +The following example defines a class that compares wrapped numeric values. Only `__eq__()` and `__lt__()` are implemented; the rest are generated automatically: -**Option 1 - Wrap** -```codebyte/python +```py from functools import total_ordering @total_ordering -class Name: - def __init__(self, first_comparison): - self.first_comparison = first_comparison +class Number: + def __init__(self, value): + self.value = value - def __eq__(self, other): - return self.first_comparison == other.first_comparison + def __eq__(self, other): + return self.value == other.value - def __lt__(self, other): - return self.first_comparison < other.first_comparison + def __lt__(self, other): + return self.value < other.value + +print(Number(3) < Number(4)) +print(Number(5) >= Number(5)) +print(Number(7) > Number(1)) ``` -**Option 2 - Call** -```codebyte/python -from functools import total_ordering -class Name: - def __init__(self, first_comparison): - self.first_comparison = first_comparison +The outout of this code is: - def __eq__(self, other): - return self.first_comparison == other.first_comparison +```shell +True +True +True +``` - def __lt__(self, other): - return self.first_comparison < other.first_comparison +## Example 2: Ordering Strings by Length -name = total_ordering(Name) -``` +This example demonstrates ordering based on string length instead of direct string comparison: -## Example -This example demonstrates that `total_ordering` defines missing rich comparison methods within a class. -```codebyte/python +```py from functools import total_ordering @total_ordering -class Age: - def __init__(self, age_number): - self.age_number = age_number +class Word: + def __init__(self, text): + self.text = text - def __eq__(self, other): - return self.age_number == other.age_number + def __eq__(self, other): + return len(self.text) == len(other.text) - def __lt__(self, other): - return self.age_number < other.age_number + def __lt__(self, other): + return len(self.text) < len(other.text) -#The __gt__ method (greater than) was not defined explicitly in the code above. That's where total_ordering can help! -print(Age(20) > Age(60)) -``` -Here is the output: -``` -False +print(Word("apple") < Word("banana")) +print(Word("kiwi") == Word("pear")) +print(Word("grape") > Word("fig")) ``` -This example demonstrates the customization capabilities when using rich comparison methods and total_ordering. -```codebyte/python -from functools import total_ordering -@total_ordering -class Sky_Color: - def __init__(self, color): - self.color = color +The output of this code is: -#The __eq__ method (equal to) is customized and defined as 'not equal to blue' within this class. Any class object that is not equal to blue will return a True boolean. - def __eq__(self, other): - return self.color != "blue" +```shell +True +True +True +``` - def __lt__(self, other): - return self.color < other.color +## Codebyte Example: Prioritizing Tasks -blue_color = "blue" -print(f"Is the sky {blue_color}?") -print(f"{blue_color == Sky_Color(blue_color)}") +The following codebyte defines a class where objects are ordered by priority value: -#The class Sky_Color does not explicitly define the '!=' operator (Not Equal To). This is automically defined by the use of total_ordering. -print(f"\nIs the sky never {blue_color}?") -print(f"{blue_color != Sky_Color(blue_color)}") -``` -This will print: -``` -Is the sky blue? -False +```codebyte/python +from functools import total_ordering -Is the sky never blue? -True +@total_ordering +class Task: + def __init__(self, name, priority): + self.name = name + self.priority = priority + + def __eq__(self, other): + return self.priority == other.priority + + def __lt__(self, other): + return self.priority > other.priority + +tasks = [ + Task("Write report", 2), + Task("Fix bugs", 5), + Task("Plan sprint", 3) +] + +tasks.sort() +for t in tasks: + print(t.name, t.priority) ``` + +Higher priority numbers are treated as greater for sorting purposes. From a1171b26b90cbccaf8d8caa28a325c08e11d4d35 Mon Sep 17 00:00:00 2001 From: Sriparno Roy <89148144+Sriparno08@users.noreply.github.com> Date: Wed, 5 Nov 2025 14:25:12 +0530 Subject: [PATCH 3/3] Minor changes --- .../functools-module/terms/total-ordering/total-ordering.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md b/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md index 604512b485b..afbed3a2abd 100644 --- a/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md +++ b/content/python/concepts/functools-module/terms/total-ordering/total-ordering.md @@ -13,7 +13,7 @@ CatalogContent: - 'paths/computer-science' --- -The **`total_ordering()`** decorator from the functools module simplifies the creation of fully ordered classes. By defining the `__eq__()` method and one additional comparison method (`__lt__()`, `__le__()`, `__gt__()`, or `__ge__()`), all other rich comparison methods are automatically generated. +In Python, the **`total_ordering()`** decorator from the `functools` module simplifies the creation of fully ordered classes. By defining the `__eq__()` method and one additional comparison method (`__lt__()`, `__le__()`, `__gt__()`, or `__ge__()`), all other rich comparison methods are automatically generated. This decorator reduces redundant code in custom classes that require complete ordering behavior for comparisons, sorting, and equality checks.