Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check all values below are not None

What is the best way to check all values below are not None. This is what I have tried:

    user = url_string.get('user', None)
    subject = url_string.get('subject', None)
    email = url_string.get('email', None)
    from_address = url_string.get('from_address', None)

    if not any(user, subject, email,from_address):
        raise Exception('missing data')
like image 853
MarkK Avatar asked Feb 19 '26 23:02

MarkK


1 Answers

Since you want all of them to be defined, the following code would be very pythonic. Since

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

https://docs.python.org/2/glossary.html

try:
    user = url_string['user']
    subject = url_string['subject']
    email = url_string.get['email']
    from_address = url_string['from_address']
except KeyError:
        raise Exception('missing data')

As mentioned in the comments, this does leave open the possibility of one of the values in the dictionary being None and there for passing the test. However, I assume you are using get('...',None) on the assumption that the dictionary doesn't contain nulls. if it does indeed contain nulls, consider Moses Koledoye's solution.

like image 55
e4c5 Avatar answered Feb 21 '26 13:02

e4c5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!