-   Programming (
-   -   python: mystery syntax (

stateless 02-22-2013 03:00 PM

python: mystery syntax
Hi. My Python skills are quite rusty, but I have to edit code somebody else wrote. I'm a little confused by this construction I found:


if not varname is None:

(I replaced the real variable with "varname" and the executed block with "...etc...")
What exact kind of check does "if not varname is None" do with varname?

dugan 02-22-2013 03:08 PM

It's the same as:


if varname is not None
Which can be run after lines like this:


varname = None
varname = 3
varname = 'a'

audriusk 02-22-2013 03:56 PM

Operator is tests for object identity. From Python documentation:

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address).
In your case the condition checks if object varname refers to is not a None object (a special singleton object, used where one needs to indicate the absence of a value).

All times are GMT -5. The time now is 09:21 PM.