0

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
ELM
  • 60
  • 9
  • So you are trying to make a function? Why would both return true (if this was possible) – Stefan Apr 26 '22 at 15:14
  • 1
    `print(b == c)` returns False, quite correctly, because c is 1 and b is 0 – Giovanni Tardini Apr 26 '22 at 15:15
  • 1
    https://stackoverflow.com/questions/49658308/how-does-the-logical-and-operator-work-with-integers – Eumel Apr 26 '22 at 15:16
  • 2
    There are no "`or` statements; `or` is an operator used in *expressions*. Python doesn't support the kind of implication you are striving for here. (You can't say that `c` has two different values like this. Equality is transtive, so if `a == b` is false, there is no way you can say that `c == a` *and* `c == b` are true, at least not without providing a broken definition of `__eq__` on a custom class.) – chepner Apr 26 '22 at 15:17
  • 1
    Unlike operators such as `+`, `-`, etc, you cannot provide your own definitions of `and` and `or`. – chepner Apr 26 '22 at 15:18

3 Answers3

0

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)
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
0

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
gimix
  • 3,431
  • 2
  • 5
  • 21
0

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.

Stuart
  • 9,597
  • 1
  • 21
  • 30