Skip to content

Sorting on Attribute with Callable for order Parameter in field #1166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
klausmcm opened this issue Jul 25, 2023 · 1 comment
Closed

Sorting on Attribute with Callable for order Parameter in field #1166

klausmcm opened this issue Jul 25, 2023 · 1 comment

Comments

@klausmcm
Copy link

klausmcm commented Jul 25, 2023

I defined a callable for the order parameter and was expecting the third assertion below to pass as well (running on Python 3.7.2)

from decimal import Decimal

from attrs import define, field, validators


@define
class TestClass:
    num: Decimal = field(
        validator=validators.instance_of(Decimal),
        eq=lambda x: 0 if x.is_nan() else x,
        order=lambda x: Decimal("-Infinity") if x.is_nan() else x,
    )


assert sorted([Decimal(1), Decimal("-Infinity")]) == [Decimal("-Infinity"), Decimal(1)]

tc1 = TestClass(num=Decimal(2))
tc2 = TestClass(num=Decimal(0))
assert sorted([tc1, tc2], key=lambda x: x.num) == [tc2, tc1]

tc1 = TestClass(num=Decimal(3))
tc2 = TestClass(num=Decimal("NaN"))
assert sorted([tc1, tc2], key=lambda x: x.num) == [tc2, tc1]

However, I get the following error

Traceback (most recent call last):
  File "test.py", line 23, in <module>
    assert sorted([tc1, tc2], key=lambda x: x.num) == [tc2, tc1]
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

This error is usually raised when trying to sort a collection containing Decimal("NaN") so the callable that I defined for order did not seem to be used when calling sorted. I'm not sure if this is a bug or if I misunderstood something.

@klausmcm klausmcm closed this as not planned Won't fix, can't repro, duplicate, stale Jul 25, 2023
@klausmcm
Copy link
Author

Sorry, what I'm asking for is what I'm supposed to define as the key parameter in sorted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant