Home > Software design >  Assigning an OR statement to a variable in python
Assigning an OR statement to a variable in python

Time:04-27

I have been looking for ways to assign a or statement to a variable, in a way that the variable can be used as a reference for other comparisons.

What i'm trying to accomplish by example:

a = 1
b = 0

c = a or b
print(a == c) #would return True
print(b == c) #would also return True

CodePudding user response:

You can change the definition of the == operator by creating a class and replacing your integer values with objects that contain each integer, so you will be able to override the equal operator with the __eq__ function. In this example, I will negate the result of the default operator to show you that you can apply whatever definition you need for that operation. The only disadvantage is that in Python, you can't override or redefine or:

class num:
    def __init__(self, n):
        self.n = n
        
    def __eq__(self, n):
        return not n==self.n

a = num(1)
b = num(0)

c = a or b
print(a == c)
print(b == c)

CodePudding user response:

You can get something like that by using functools.partial and operator.or_:

a=True
b=False
c = partial(or_, a,b)
c()
True

But beware, a and b are evaluated at definition time:

a=False
c()
True

CodePudding user response:

What you seem to want is somewhat close to the way sets work, with the operator | replacing or (which cannot be overridden):

a = {0}
b = {1}
c = a | b     # or a.union(b)
a.issubset(c)   # True
b.issubset(c)   # True
{3}.issubset(c)   # False

You could in principle make your own class that extends set:

class Singleton(set):
    def __init__(self, n):
        super().__init__([n])    
        
    def __eq__(self, other):
        return self.issubset(other) or other.issubset(self)
    
a = Singleton(1)
b = Singleton(0)
c = a | b
print(a == c) # True
print(b == c) # True

But it is doubtful whether the confusing code this generates would ever be worth it.

  • Related