strange test for None

Peter Otten __peter__ at web.de
Sat Feb 3 09:20:04 EST 2007


karoly.kiripolszky wrote:

> in my server i use the following piece of code:
> 
>             ims = self.headers["if-modified-since"]
>             if ims != None:
>                 t = int(ims)
> 
> and i'm always getting the following error:
> 
>     t = int(ims)
> ValueError: invalid literal for int(): None
> 
> i wanna know what the hell is going on... first i tried to test using
> is not None, but it makes no difference.
> 
> sorry i forgot, it's interpreter 2.4.4.

Instead of the None singleton...

>>> int(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: int() argument must be a string or a number

...you seem to have the /string/ "None" in your dictionary

>>> int("None")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): None

While the immediate fix would be

if ims != "None":
    t = int(ims)

there is probably an erroneous

self.header["if-modified-since"] = str(value)

elsewhere in your code that you should replace with

if value is not None:
    self.header["if-modified-since"] = str(value)

The quoted portion would then become

if "if-modified-since" in self.header:
    t = int(self.headers["if-modified-since"])

Peter



More information about the Python-list mailing list