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


Question

Suppose I have a class with a string instance attribute. Should I initialize this attribute with "" value or None? Is either okay?

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

or

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

Edit: What I thought is that if I use "" as an initial value, I "declare" a variable to be of string type. And then I won't be able to assign any other type to it later. Am I right?

Edit: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of S.Lott: "Since nothing in Python is "declared", you're not thinking about this the right way."

1
59
3/1/2012 12:56:54 AM

Accepted Answer

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'>
67
9/24/2009 12:32:46 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon