How to throw exception when comparing with None on Python 2.7? -
in python 2.7:
expression 1 (fine):
>>> 2 * none traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: unsupported operand type(s) *: 'int' , 'nonetype'
expression 2 (fine):
>>> none none true
expression 3 (bad):
>>> 2 < none false
expression 4 (bad):
>>> none<none false
expression 5 (bad):
>>> none==none true
i want somehow force expressions 3, 4 , 5 throw typeerror (same in expression 1).
python 3.4 there - expression 5 returns true.
i need in 2.7.
my use case (if interested):
i'v made application evaluates expressions (example):
d = a+b e = int(a>b) f = if a<b else b if b<c else c
expressions based on values (a, b , c) comes deserialized json. most of time values (a, b , c) integers, (when value missing) none. when value missing , used in expressions expression should return none (i thinking catching typeerror exception).
in case when a=none, b=1, c=2, exptected result is: d=none, e=none, f=none.
in case when a=1, b=2, c=none, expected result is: d=3, e=0, f=1
you can't change behavior of none
. however, can implement own type has behavior want. starting point:
class calcnum(object): def __init__(self, value): self.value = value def __add__(self, o): return calcnum(self.value + o.value) def __lt__(self, o): if self.value none or o.value none: # pick one: # return calcnum(none) raise typeerror("can't compare nones") return calcnum(self.value < o.value)
Comments
Post a Comment