Why is str(None) == 'None' and not an empty string?

Ian Kelly ian.g.kelly at gmail.com
Thu Aug 29 06:43:16 EDT 2013


On Wed, Aug 28, 2013 at 6:21 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Wed, 28 Aug 2013 01:57:16 -0700, Piotr Dobrogost wrote:
>
>> Hi!
>>
>> Having repr(None) == 'None' is sure the right thing but why does
>> str(None) == 'None'? Wouldn't it be more correct if it was an empty
>> string?
>
>
> Why do you think an empty string is more correct? Would you expect
> str([]) or str(0.0) or str({}) to also give an empty string?
>
>
> I can't see any reason for str(None) to return the empty string.

I've had many occasions where it would have been convenient for
str(None) to return the empty string, e.g. when exporting tabular data
that includes null values from a database to a spreadsheet.  Generally
it's safe to just call str() on the data, except that I'd rather empty
cells just be empty rather than spamming the word "None" all over the
place, so I end up having to do something like (str(value) if value is
not None else '') instead.  Not a major inconvenience, but enough to
make me wonder if there could be a better way.

I would not expect str([]) or str(0.0) or str({}) to return an empty
string.  I would expect these to return '[]', '0.0', and '{}'
respectively, which are all consistent with how str operates on other
values of their respective types.  None is a singleton though, so it's
not constrained by how other instances of NoneType behave.



More information about the Python-list mailing list