Python: using property getter as a callable function?

Question:

Getters for Python’s properties are not callable, for example as a ‘key’ in list.sort. Is it right to simply use get to use the property as a callable getter method?

import random


class Numbers:
    def __init__(self, num):
        self._num = num

    # getter property is not callable (e.g., in list.sort())
    @property
    def num(self):
        return self._num

    def __str__(self):
        return str(self._num)


nums = []

print("nSorted numbers")
nums.sort(key=Numbers.num.__get__)  # Error raised without __get__
for n in nums:
    print(n, end=' ')

I appreciate if someone would confirm this is the right way or suggest a better way of doing this. Thank you!

Asked By: yota

||

Answers:

You can get access to the property’s getter via its fget attribute.

nums.sort(key=Numbers.num.fget)

It might be simpler, though, to simply provide a __lt__ method that compares Numbers instances by their _num attributes:

# Ignoring issues of other not being an instance of Numbers itself...
def __lt__(self, other):
    return self._num < other._num

    
Answered By: chepner

Use lambda, then it doesn’t matter whether it’s an ordinary attribute or a getter.

nums.sort(key = lambda n: n.num)
Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.