CodexBloom - Programming Q&A Platform

Sorting a List of Custom Objects by Multiple Attributes in Python - AttributeError on Missing Fields

👀 Views: 71 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
python sorting object-oriented Python

I'm having trouble with Could someone explain I'm stuck on something that should probably be simple... I'm working on a personal project and I'm trying to sort a list of custom objects in Python based on multiple attributes, but I'm running into an `AttributeError` when one of the objects is missing a field... My current implementation uses a lambda function for sorting, but I want to handle cases where an attribute might not exist in some objects without raising an error. Here's a simplified version of my class and the code I'm using: ```python class Person: def __init__(self, name, age, city=None): self.name = name self.age = age self.city = city people = [ Person('Alice', 30, 'New York'), Person('Bob', 25), # Missing city Person('Charlie', 35, 'Los Angeles'), Person('David', 28, None) # City is None ] # Attempting to sort by city first, then age sorted_people = sorted(people, key=lambda p: (p.city or '', p.age)) ``` When I run the above code, I get an `AttributeError` if any `Person` object does not have the `city` attribute. I tried using the `getattr` function like this: ```python sorted_people = sorted(people, key=lambda p: (getattr(p, 'city', ''), p.age)) ``` However, this doesn't seem to work as intended. Even though I provide a default value, it appears that I still get an `AttributeError` for objects where `city` is not defined. I'm assuming this is due to the fact that my lambda function is still trying to access the attribute directly. Is there a better way to handle sorting with missing attributes in custom objects without encountering errors? I'd appreciate any tips on best practices for sorting lists like this in Python. Any help would be greatly appreciated! For reference, this is a production desktop app. Any pointers in the right direction? Is there a simpler solution I'm overlooking? I'm working on a web app that needs to handle this. I appreciate any insights!