1

I am writing a wrapper for SQL Conditions ( so that I can use them in my where statement that I also have a wrapper for ).

Idea is that all of them would be valid :

>> condition_a = Condition("x","=","5")
>> condition_b = Condition("y",">","6")
>> c = condition_a & condition_b
which should give me " x = 5 AND y > 6 "

that is fine so far - I can do so by overloading and, and or.

I don't know what I should overload to have ( working like this ?

>> condition_a = Condition("x","=","5")
>> condition_b = Condition("y",">","6")
>> condition_c = Condition("z",">","7")
>> d = condition_c & ( condition_a |  condition_b )
which should give me " z > 7 AND ( x = 5 OR y > 6 ) "

Sceleton for my condition class is :

class Condition( object ) :
    def __init__( self , args ) :
        ....

    def __and__( self , other ) :
      ...

    def __or__( self , other ) : 
       ...

How can i do that?

3
  • Not really a duplicate, but take a look at stackoverflow.com/questions/15719172/… Commented Nov 9, 2017 at 16:29
  • IMO condition_a | condition_b should result in a new ConditionGroup like object as an operand to following computation. Commented Nov 9, 2017 at 16:58
  • @georgexsh can you give an example because I think I am having this problem atm Commented Nov 9, 2017 at 17:06

1 Answer 1

2

You don't need to overload (, and you can not do that.

As you are generating SQL statements, I guess extra parentheses is acceptable, and less error prone:

class Condition( object ) :
    def __init__( self , *args ) :
        self.args = args

    def __str__(self):
        return '({})'.format(' '.join(map(str, self.args)))

    def __and__( self , other ) :
        return Condition(self, 'and', other)

    def __or__( self , other ) :
        return Condition(self, 'or', other)

condition_a = Condition("x","=","5")
condition_b = Condition("y",">","6")
condition_c = Condition("z",">","7")
d = condition_c & ( condition_a |  condition_b )
print(d)

yields:

((z > 7) and ((x = 5) or (y > 6)))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.