تخطَّ إلى المحتوى

Unguarded first element (ARCH2078)

هذا المحتوى غير متوفر بلغتك بعد.

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.

def first_admin(users):
admins = [u for u in users if u.role == "admin"]
return admins[0]
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.