2

I'm using Pycharm to develop python scripts.

I have a list of class and want to sort this list by a class property.

However, when I use:

results: list[HotelInfo] = get_result()
results.sort(key=lambda x: x.price)

PyCharm's type hint shows that "x" is of type "any" and can't get class property.

Even if I set x: CLASS_NAME, the lambda seems doesn't display correct type.

enter image description here

How can I solve this problem in PyCharm?

1 Answer 1

0

As Martijn Pieters♦ points out in his answer you can type hint a callable object and pass that as your function.

results: list[HotelInfo] = get_result()
get_price: Callable[[HotelInfo], int] = lambda hotel: hotel.price
results.sort(key=get_price)

This works for me in a local example and PyCharm recognizes the types.

strings = ["Hello World", "Goodbye World :(", "Cookies"]

func: Callable[[str], int] = lambda s: len(s)
print(sorted(strings, key=func))
Sign up to request clarification or add additional context in comments.

1 Comment

It's not work, I use your example ... ] = lambda hotel: hotel.price , pycharm still show the hotel is any

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.