2

The behavior desired is this:

In [653]: choice = 'A'

In [654]: not(choice)
Out[654]: 'B'

Is there a robust way in which this can be done? Currently I'm using simple hacks like these.

def other(choice):
    if choice == 'A':
        return 'B'
    else:
        return 'A'

In [635]: other('B')
Out[635]: 'A'

d = dict()
d['A'] = 'B'
d['B'] = 'A'

In [652]: d['A']
Out[652]: 'B'
Shyam Sunder
  • 1,200
  • 2
  • 11
  • 23
  • This sounds like enums, which aren't in Python. I don't think Python really felt the need to include enums, and I've never felt the need to have enums in Python, but check this enums in Python question out: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python – Prashant Kumar Jan 30 '13 at 15:34
  • 2
    I am not sure if you are asking about overloading the "not" boolean operator. this was proposed and not accepted, see PEP335. – llazzaro Jan 30 '13 at 15:37

2 Answers2

4

Have a look at special method names. You may need to implement more of them.

class myBool():
    def __init__(self, val):
        self.value = val

    def __repr__(self):
        return self.value

    def __invert__(self):
        if self.value == 'A':
            return 'B'
        else:
            return 'A'

def main():
    a = myBool('A')
    print(a)
    print(~a)

if __name__ == '__main__':
    main()
Dimitris Leventeas
  • 1,622
  • 2
  • 16
  • 29
0

There are no variables in Python. There are only names, and names can be bound to any object of any type.

Note that this is perfectly valid in Python:

a = 'hello'
a = 1
a = True
a = 2.2

That doesn't mean that the objects referenced by a don't have a type, they do, but the name itself does not.

That said, you could write a class that implements the __setattr__ member and restricts some member names to be into a specific set, but I don't think that it is worth it.

And certainly it is not pythonic. If you feel uncomfortable with that then you should switch to a stronger typed language.

rodrigo
  • 94,151
  • 12
  • 143
  • 190