def location_candidates(profile, preferred=None): candidates = [] seen = set() def add(val): if val is None: return s = str(val).strip().lower().replace(' ', '_') if s and s not in seen: seen.add(s) candidates.append(s) if preferred: add(preferred) sources = [] try: if profile and profile.connection and profile.connection.location: sources.append(profile.connection.location) except Exception: pass try: if profile and profile.location: sources.append(profile.location) except Exception: pass for source in sources: add(getattr(source, 'id', None)) add(getattr(source, 'country_name', None)) add(getattr(source, 'name', None)) add(getattr(source, 'code', None)) add(getattr(source, 'country_code', None)) return candidates