LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   python: mystery syntax (http://www.linuxquestions.org/questions/programming-9/python-mystery-syntax-4175451312/)

stateless 02-22-2013 02: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:

Code:

if not varname is None:
    ...etc...

(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 02:08 PM

It's the same as:

Code:

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

Code:

varname = None
varname = 3
varname = 'a'


audriusk 02-22-2013 02:56 PM

Operator is tests for object identity. From Python documentation:
Quote:

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 02:16 AM.