Unguarded first element (ARCH2078)
Esta página aún no está disponible en tu idioma.
Key python.performance.first-or-default-null · Severity warning · Category performance
Accessing [0] of a filtered collection without an emptiness check raises IndexError when the result is empty. Supply a default with next.
Incorrect
Section titled “Incorrect”def first_admin(users): admins = [u for u in users if u.role == "admin"] return admins[0]Correct
Section titled “Correct”def first_admin(users): return next((u for u in users if u.role == "admin"), None)Take the first match with next(generator, None) so an empty result yields a default.