Initialize a string variable in Python: "" or None?

It depends. If you want to distinguish between no parameter passed in at all, and an empty string passed in, you could use None.


Another way to initialize an empty string is by using the built-in str() function with no arguments.

str(object='')

Return a string containing a nicely printable representation of an object.

...

If no argument is given, returns the empty string, ''.

In the original example, that would look like this:

def __init__(self, mystr=str())
   self.mystr = mystr

Personally, I believe that this better conveys your intentions.

Notice by the way that str() itself sets a default parameter value of ''.


If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway.

If the value must be provided by the caller of __init__, I would recommend not to initialize it.

If "" makes sense as a default value, use it.

In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.

>>> x = None
>>> print type(x)
<type 'NoneType'>
>>> x = "text"
>>> print type(x)
<type 'str'>
>>> x = 42
>>> print type(x)
<type 'int'>

None is used to indicate "not set", whereas any other value is used to indicate a "default" value.

Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.

Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.

Tags:

Python