Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one of variables is set to None

Tags:

python

I recently had to implement a small check for any variables that might have not been initialized (and their default value is None). I came up with this:

if None in (var1, var2, var3):     error_out() 

While, in my eyes, bordering on beautiful, I was wondering - is this a good way to do it? Is this the way to do it? Are there any cases in which this would produce some unexpected results?

like image 677
maligree Avatar asked Jul 05 '11 10:07

maligree


People also ask

How do you know if a variable is not None?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

How do I know if my value is NoneType?

To check whether a variable is None or not, use the is operator in Python. With the is operator, use the syntax object is None to return True if the object has the type NoneType and False otherwise.

How do you check if two variables are None in Python?

Use the is operator to check if a variable is None in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None .

Is None or not Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.


1 Answers

First things first: your code is valid, readable, concise... so it might not be the way to do it (idioms evolves with time and new language features) but it certainly is one of the way to do it in a pythonic way.

Secondly, just two observations:

The standard way to generate errors in python is to raise Exceptions. You can of course wrap your exception-raising within a function, but since it's quite unusual I was just wondering if you chose this design for some specific reason. Since you can write your own Exception class, even boilerplate code like logging an error message to file could go within the class itself rather than in the wrapping function.

The way you wrote your test is such that you won't be able to assign None as a value to your variables. This might be not a problem now, but might limit your flexibility in the future. An alternative way to check for initialisation could be to simply not declare an initial value for the variable in question and then do something along the lines of:

try:     self.variable_name except NameError:     # here the code that runs if the variable hasn't been initialised finally:     # [optional] here the code that should run in either case 
like image 195
mac Avatar answered Oct 16 '22 21:10

mac