Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if not someobj:
- #do something
- if someobj == None:
- #do something
- >>> class A(object):
- ... def __repr__(self):
- ... return 'A()'
- ... def __nonzero__(self):
- ... return False
- >>> class B(object):
- ... def __repr__(self):
- ... return 'B()'
- ... def __len__(self):
- ... return 0
- >>> class C(object):
- ... def __repr__(self):
- ... return 'C()'
- ... def __cmp__(self, other):
- ... return 0
- >>> class D(object):
- ... def __repr__(self):
- ... return 'D()'
- ... def __eq__(self, other):
- ... return True
- >>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
- ... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' %
- ... (repr(obj), bool(obj), obj == None, obj is None)
- '': bool(obj) -> False, obj == None -> False, obj is None -> False
- (): bool(obj) -> False, obj == None -> False, obj is None -> False
- []: bool(obj) -> False, obj == None -> False, obj is None -> False
- {}: bool(obj) -> False, obj == None -> False, obj is None -> False
- 0: bool(obj) -> False, obj == None -> False, obj is None -> False
- 0.0: bool(obj) -> False, obj == None -> False, obj is None -> False
- A(): bool(obj) -> False, obj == None -> False, obj is None -> False
- B(): bool(obj) -> False, obj == None -> False, obj is None -> False
- C(): bool(obj) -> True, obj == None -> True, obj is None -> False
- D(): bool(obj) -> True, obj == None -> True, obj is None -> False
- None: bool(obj) -> False, obj == None -> True, obj is None -> True
- - Comparisons to singletons like None should always be done with
- 'is' or 'is not', never the equality operators.
- Also, beware of writing "if x" when you really mean "if x is not None"
- -- e.g. when testing whether a variable or argument that defaults to
- None was set to some other value. The other value might have a type
- (such as a container) that could be false in a boolean context!
- if not False:
- print "False is false."
- if not 0:
- print "0 is false."
- if not []:
- print "An empty list is false."
- if not ():
- print "An empty tuple is false."
- if not {}:
- print "An empty dict is false."
- if not "":
- print "An empty string is false."
- >>> False == 0
- True
- >>> False == ()
- False
- foo = bar and spam or eggs
- if bar:
- foo = bar
- else:
- foo = eggs
- if not spam:
- print "Sorry. No SPAM."
- if spam == None:
- print "Sorry. No SPAM here either."
- - Comparisons to singletons like None should always be done with
- 'is' or 'is not', never the equality operators.
Add Comment
Please, Sign In to add comment