pythonrecursiontry-exceptrecursionerror

Why can't a reference to a not imported module be made if the same module is imported in error-handling?


Given this python script:

def s():
    try:
        time.sleep(1)
    except NameError:
        import time
        s()


for i in range(10):
    s()
    print(i)

This gives me a RecursionError, but I don't see why because I would expect it to:

  1. Call the s function
  2. Cause a NameError in the try clause, as time is not yet imported
  3. Import time in the except clause
  4. Call itself
  5. Succeed in the try clause, sleeping for 1 second
  6. print 0
  7. Succeed in the try clause all successive times, printing numbers up to 9 with 1 second in between them.

I cannot see why it would call the s() function recursively more than 2 times.

For clarification purposes:

  1. I only want to import the module if it wasn't already imported.
  2. I only want to import the module if the function is called.

Solution

  • Since the import is inside a function, names it defines are local to that function's scope by default. To make it global, use global time.

    def s():
        global time
        try:
            time.sleep(1)
        except NameError:
            import time
            s()