Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if one or more values is None and knows which ones are

I have a Python app with a Firebase-database backend.

When I retrieve the data from my database, I want to check if those values are available (if not, that means that the database is somehow corrupted, as mandatories fields are missing)

My current implementation is the following:

self.foo = myDbRef.get('foo')
self.bar =  myDbRef.get('bar')
self.bip =  myDbRef.get('bip')
self.plop = myDbRef.get('plop')

if self.foo is None or self.bar is None or self.bip is None or self.plop is None:
    self.isValid = False
    return ErrorCode.CORRUPTED_DATABASE

This works fine, is compact, but have a major issue: I will get the information that the database is corrupted, but not what field is missing (could be just one of them, or more, or all !)

The idiomatic approach should be

if self.foo is None:
    self.isValid = False
    return ErrorCode.CORRUPTED_DATABASE, "FOO IS MISSING" # could be a string, an enum value, whatever, I have the information

if self.bar is None:
    self.isValid = False
    return ErrorCode.CORRUPTED_DATABASE, "BAR IS MISSING"

if self.bip is None:
    self.isValid = False
    return ErrorCode.CORRUPTED_DATABASE, "BIP IS MISSING"

But this is not pretty, not factorized (All my 'init from db' functions use the same pattern... I don't want to multiply my number of lines by a factor of 10 for such a case).

This is not a '100% python' question, but I hope the langage has something for me to handle this like a boss (it's python: it usually does !)

like image 231
MisterPatate Avatar asked Nov 08 '22 10:11

MisterPatate


1 Answers

You could extract the checks into a generator and leave the flag and return statements outside.

def invalid_fields():
    if self.foo is None: yield "FOO"
    if self.bar is None: yield "BAR"
    if self.bip is None: yield "BIP"

invalid = list(invalid_fields())
if invalid:
    self.isValid = False
    return ErrorCode.CORRUPTED_DATABASE, "MISSING {}".format(", ".join(invalid))

This has the advantage of telling you about all the missing fields if there are more than one.

like image 64
John Kugelman Avatar answered Nov 14 '22 22:11

John Kugelman