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:
- Call the
sfunction - Cause a NameError in the try clause, as time is not yet imported
- Import time in the except clause
- Call itself
- Succeed in the try clause, sleeping for 1 second
- print
0 - 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:
- I only want to import the module if it wasn't already imported.
- I only want to import the module if the function is called.
Since the
importis inside a function, names it defines are local to that function's scope by default. To make it global, useglobal time.