def location_candidates(profile, preferred=None): candidates = [] seen = set() def add_location_id(source): if isinstance(source, dict): value = source.get('id') or source.get('location_id') else: value = getattr(source, 'id', None) if value is None or isinstance(value, bool): return try: location_id = int(value) except (TypeError, ValueError): return if location_id not in seen: seen.add(location_id) candidates.append(location_id) if preferred: try: add_location_id({'id': int(preferred)}) except (TypeError, ValueError): pass sources = [] try: if profile and profile.location: sources.append(profile.location) except Exception: pass try: if profile and profile.connection and profile.connection.location: sources.append(profile.connection.location) except Exception: pass for source in sources: add_location_id(source) return candidates