Skip to content

Commit 7fb5ae5

Browse files
author
Davies Liu
committed
[SPARK-8573] [SPARK-8568] [SQL] [PYSPARK] raise Exception if column is used in booelan expression
It's a common mistake that user will put Column in a boolean expression (together with `and` , `or`), which does not work as expected, we should raise a exception in that case, and suggest user to use `&`, `|` instead. Author: Davies Liu <davies@databricks.com> Closes apache#6961 from davies/column_bool and squashes the following commits: 9f19beb [Davies Liu] update message af74bd6 [Davies Liu] fix tests 07dff84 [Davies Liu] address comments, fix tests f70c08e [Davies Liu] raise Exception if column is used in booelan expression
1 parent d96d7b5 commit 7fb5ae5

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

python/pyspark/sql/column.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,11 @@ def over(self, window):
396396
jc = self._jc.over(window._jspec)
397397
return Column(jc)
398398

399+
def __nonzero__(self):
400+
raise ValueError("Cannot convert column into bool: please use '&' for 'and', '|' for 'or', "
401+
"'~' for 'not' when building DataFrame boolean expressions.")
402+
__bool__ = __nonzero__
403+
399404
def __repr__(self):
400405
return 'Column<%s>' % self._jc.toString().encode('utf8')
401406

python/pyspark/sql/tests.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,14 @@ def test_explode(self):
164164
self.assertEqual(result[0][0], "a")
165165
self.assertEqual(result[0][1], "b")
166166

167+
def test_and_in_expression(self):
168+
self.assertEqual(4, self.df.filter((self.df.key <= 10) & (self.df.value <= "2")).count())
169+
self.assertRaises(ValueError, lambda: (self.df.key <= 10) and (self.df.value <= "2"))
170+
self.assertEqual(14, self.df.filter((self.df.key <= 3) | (self.df.value < "2")).count())
171+
self.assertRaises(ValueError, lambda: self.df.key <= 3 or self.df.value < "2")
172+
self.assertEqual(99, self.df.filter(~(self.df.key == 1)).count())
173+
self.assertRaises(ValueError, lambda: not self.df.key == 1)
174+
167175
def test_udf_with_callable(self):
168176
d = [Row(number=i, squared=i**2) for i in range(10)]
169177
rdd = self.sc.parallelize(d)
@@ -408,7 +416,7 @@ def test_column_operators(self):
408416
self.assertTrue(isinstance((- ci - 1 - 2) % 3 * 2.5 / 3.5, Column))
409417
rcc = (1 + ci), (1 - ci), (1 * ci), (1 / ci), (1 % ci)
410418
self.assertTrue(all(isinstance(c, Column) for c in rcc))
411-
cb = [ci == 5, ci != 0, ci > 3, ci < 4, ci >= 0, ci <= 7, ci and cs, ci or cs]
419+
cb = [ci == 5, ci != 0, ci > 3, ci < 4, ci >= 0, ci <= 7]
412420
self.assertTrue(all(isinstance(c, Column) for c in cb))
413421
cbool = (ci & ci), (ci | ci), (~ci)
414422
self.assertTrue(all(isinstance(c, Column) for c in cbool))

0 commit comments

Comments
 (0)