Programming Python 3rd Edition by Mark Lutz has example code (below) where a variable seems to be assigned with options ("or") but what the criteria for selecting the options is not clear.
The explanation is almost non-existent but I think this is to do with feeding in a variable number of command line argments
Can someone clarify the use of "or" in line:

**self.verbose = self.getopt('-v') or self.getenv('VERBOSE') **

Thank you

import sys, os, traceback
class AppError(Exception): pass                           # errors raised here

class App:                                                # the root class
    def __init__(self, name=None):
        self.name    = name or self.__class__.__name__    # the lowest class
        self.args    = sys.argv[1:] 
        self.env     = os.environ
        self.verbose = self.getopt('-v') or self.getenv('VERBOSE')   
        self.input   = sys.stdin
        self.output  = sys.stdout 
        self.error   = sys.stderr                     # stdout may be piped
    def closeApp(self):                               # not __del__: ref's?
        pass                                          # nothing at this level
    def help(self):
        print self.name, 'command-line arguments:'    # extend in subclass
        print '-v (verbose)'

    ##############################
    # script environment services
    ##############################

    def getopt(self, tag):
        try:                                    # test "-x" command arg
            self.args.remove(tag)               # not real argv: > 1 App?
            return 1                   
        except:
            return 0
    def getarg(self, tag, default=None):
        try:                                    # get "-x val" command arg
            pos = self.args.index(tag)
            val = self.args[pos+1]
            self.args[pos:pos+2] = []
            return val
        except:
            return default                      # None: missing, no default

Looks like method getenv(self, tag_str) is missing in the code.

Method below:

def getenv(self, name, default=''):
        try:                                    # get "$x" environment var
            return self.env[name]
        except KeyError:
            return default

An or operation is evaluated left-to-right. In this case, if self.getopt('-v') returns 1 then the user entered -v on the command line, in which case we set self.verbose to True and go on to the next statement. If there was no -v on the command line, we evaluate the second half of the or by checking environment variable VERBOSE. If VERBOSE is some sort of True (not 0, not null-string, not None) then again we set self.verbose. If both cases are some sort of False then so is self.verbose.

What you are seeing here is a funky use of or for control flow instead of a typical boolean operator. It relies on the fact that or is evaluated left-to-right and if operand 1 is True then Python doesn't even look at operand 2.

Thank you - that makes sense.
The right hand side operation can over-ride what the basic rules of assignment to the left side are desribed as.
For a text book example it seems not to be very Pythonic and relies on future versions not picking this up as an error.

A test ...

print(True or True)   # True
print(True or False)  # True
print(False or True)  # True
print(False or False) # False

print('-'*12)

# exclusive or ^
print(True ^ True)   # False
print(True ^ False)  # True
print(False ^ True)  # True
print(False ^ False) # False

print('-'*12)

print(True and True)   # True
print(True and False)  # False
print(False and True)  # False
print(False and False) # False
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.