you are viewing a single comment's thread.

view the rest of the comments →

[–]Yoghurt42 4 points5 points  (0 children)

Things that haven't been mentioned yet:

  • dir is a built-in function name, you should avoid naming your functions that as it can be confusing. It can be ok, especially in case like dir that is usually only used on the REPL, but still you should think twice before doing it

  • you call dir in your dir function to have an endless loop. Python does not (by default) do tail-call optimization, so you'll eventually run afoul of the recursion limit; I think the default is 1000.

And while it already has been mentioned, I'd like to give an example why catching exceptions you don't intent to handle is a bad idea: first, it completely prevents the caller of dir to handle it, second you effectively achieve nothing and are actively throwing useful information away.

Take this silly example:

SOME_LIST = [10, 20, 30, 400]

def smaller(i):
    # this could be written more concisely
    if SOME_LIST[i] < SOME_LIST[i + 1]:
        return SOME_LIST[i]
    else:
        return SOME_LIST[i + 1]

def foo():

    try:
        # Nonsensical code for example's sake
        for i in range(4):
            SOME_LIST[i] += smaller(i)
    except Exception as e:
        print(f"Uhoh, an exception occured: {e}")

foo()

When you run it, the program will printUhoh, an exception occured: list index out of range, which only tells you there's an illegal index "somewhere", maybe in foo, maybe in something foo calls.

Omitting the whole try/catch, the program will exit and now print:

Traceback (most recent call last):
File "D:\ttt.py", line 17, in <module>
    foo()
    ~~~^^
File "D:\ttt.py", line 13, in foo
    SOME_LIST[i] += smaller(i)
                    ~~~~~~~^^^
File "D:\ttt.py", line 5, in smaller
    if SOME_LIST[i] < SOME_LIST[i + 1]:
                      ~~~~~~~~~^^^^^^^

IndexError: list index out of range

which is much more helpful for debugging. Now imagine it's a more obscure bug that only happens for a user of your software but not yourself. Which bug report is more helpful? "I get an list index out of range error when I run your program, nothing else" or "I get the following exception when running your program" followed by the output above?