Skip to content

Override __nonzero__ and __bool__ to try and forbid the use of logical and/or/not in ThOr expressions

Olli Lupton requested to merge olupton_thor_python_tweak into master

Using and, or and not in cut expressions when &, | and ~ should have been used can result in bugs:

>>> from Functors import PT, PHI
>>> (PT > 1) & (PHI > 0)
"( ( PT > 1 ) & ( PHI > 0 ) )"
>>> (PT > 1) and (PHI > 0)
"( PHI > 0 )"
>>> (PT > 1) or (PHI > 0)
"( PT > 1 )"

This MR tries to turn the use of and, or and not into a configuration-parse-time error with ThOr.

>>> from Functors import PT, PHI
>>> (PT > 1) & (PHI > 0)
"( ( PT > 1 ) & ( PHI > 0 ) )"
>>> (PT > 1) and (PHI > 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/olupton/stack/Rec/Phys/FunctorCore/python/Functors/grammar.py", line 182, in __nonzero__
    "FunctorBase.__nonzero__ should not be called! This likely means that you used `and`, `or` or `not` when you should have used `&`, `|` or `~`."
Exception: FunctorBase.__nonzero__ should not be called! This likely means that you used `and`, `or` or `not` when you should have used `&`, `|` or `~`.
>>> (PT > 1) or (PHI > 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/olupton/stack/Rec/Phys/FunctorCore/python/Functors/grammar.py", line 182, in __nonzero__
    "FunctorBase.__nonzero__ should not be called! This likely means that you used `and`, `or` or `not` when you should have used `&`, `|` or `~`."
Exception: FunctorBase.__nonzero__ should not be called! This likely means that you used `and`, `or` or `not` when you should have used `&`, `|` or `~`.
>>> not (PT > 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/olupton/stack/Rec/Phys/FunctorCore/python/Functors/grammar.py", line 182, in __nonzero__
    "FunctorBase.__nonzero__ should not be called! This likely means that you used `and`, `or` or `not` when you should have used `&`, `|` or `~`."
Exception: FunctorBase.__nonzero__ should not be called! This likely means that you used `and`, `or` or `not` when you should have used `&`, `|` or `~`.
>>> (PT > 1) & (PHI > 0)
"( ( PT > 1 ) & ( PHI > 0 ) )"
>>> (PT > 1) | (PHI > 0)
"( ( PT > 1 ) | ( PHI > 0 ) )"
>>> ~(PT > 1)
"~( PT > 1 )"

cc: @rmatev @sstahl

Edited by Olli Lupton

Merge request reports