yaska
yaska

Reputation: 225

How come this code in python is valid? There is no if matching the else

There is no if statement matching one of the else: statement. Does having a try-except within an if block affect the indentation?

if 0 != sys.argv[1].find("clean"): #Dont check if we are cleaning!
if sys.platform.startswith("win"):
    try:
        files = O.listdir(O.path.join(libdirs))
        print "files is ",files
    except:
        raise Exception("The FMI Library binary cannot be found at path: "+str(O.path.join(libdirs)))
    for file in files:
        if "fmilib_shared" in file and not file.endswith("a"):
            print "was true for ", file
            shutil.copy2(O.path.join(libdirs,file),O.path.join(".","src","pyfmi"))
            fmilib_shared = O.path.join(".","src","pyfmi",file)
            print "fmilib_shared is ",fmilib_shared
            break
    else: # THIS IS THE ELSE BLOCK IN QUESTION
        print "We have entered the else block in question"
        raise Exception("Could not find FMILibrary at: %s"%libdirs)
    print "copy_gcc_lib flying sheep ", copy_gcc_lib    
    if copy_gcc_lib:
        path_gcc_lib = ctypes.util.find_library("libgcc_s_dw2-1.dll")
        if path_gcc_lib != None:
            shutil.copy2(path_gcc_lib,O.path.join(".","src","pyfmi"))
            gcc_lib = O.path.join(".","src","pyfmi","libgcc_s_dw2-1.dll")

The code is from the setup.py file of the PyFMI library

Upvotes: 3

Views: 119

Answers (1)

Christian Winther
Christian Winther

Reputation: 1123

The else statement is connected to the for loop, not the except block. Using an else clause on a for loop is perfectly fine and it will be executed if the loop exhaust the list it is iterating over. For more documentation, see https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

What happens in the code is that if files = ... causes an exception, it will be caught and an informative message will be printed together with a new exception (in this case the for loop will never be executed). If there is No exception, the for loop will iterate over the files searching for one specifically. If this file is not found, the else clause on the for loop will be executed and an exception raised. However, if the file is found, the break statement will cause the for loop to terminate prematurely and thus the else clause will not be executed.

To answer your question, a try-except block does not affect the indentation.

Upvotes: 4

Related Questions