Forum Archive

Console crash with settrace

ErickDaGamer

By running the following program line by line in the console, you can crash Pythonista:

import sys
sys.settrace(lambda: 0)
def s(): return False

Edit: It does not crash whenever you save it to a file and run it from there.
Edit2: I think it crashes the program if you do something after settrace. For example:

import sys
def s(): False
sys.settrace(s)
s() # Crashes the program
JonB

Seems to me you have not implemented a valid tracer function. See the docs in sys (expand below):

Trace functions should have three arguments: frame, event, and arg. frame is the current stack frame. event is a string: 'call', 'line', 'return', 'exception' or 'opcode'. arg depends on the event type.

The trace function is invoked (with event set to 'call') whenever a new local scope is entered; it should return a reference to a local trace function to be used for the new scope, or None if the scope shouldn’t be traced.

The local trace function should return a reference to itself (or to another function for further tracing in that scope), or None to turn off tracing in that scope.

Your trace function needs to look like

def tracefun(frame, event, arg):
    # do your tracing here
    return tracefun # or return None

Your function accepted no arguments, and returned an integer, not a callable or None.

ErickDaGamer

Wouldn’t it have to raise TypeError instead? This code has the same issue, but doesn’t crash Pythonista:

def s(a, b, c): return [a, b, c]
s(1)

It just raises TypeError.
Plus, the settrace issue only works in the console. It doesn’t crash Pythonista if it’s in a file.

JonB

Have you tried it with a proper function?

The underlying error handling in pythonista is different in the console vs a file (in a file, the graphical error popup is shown, while in the console it just prints the error). Calling a function from the console is also different than using settrace -- since the latter sets the underlying cpython trace mechanism, which might expect a valid function.