Return statement outside function could do same as exit function

statement

return x

outside a function could have same effect as

exit(x)

This would be intuitive, because exit makes program end its execution and return value same way like return makes function end its execution and return value.

1 Like

But they are not equivalent. sys.exit() exits the programme no matter
how many function calls deep you are. “return” only exits the topmost
function.

(Also, “return” is a function of the language itself. sys.exit() is just
itself a function which raises a particular exception, which isn’t
normally caught, thus exiting the programme. I’m just nitpicking
though.)

One reason I’d be unhappy about your suggestion is that if I put a
“return” outside a function, I’ve made a mistake. I welcome the compiler
telling me so. Because “return” means “exit this function”, and if I put
it outside a function I’ve mucked up.

Cheers,
Cameron Simpson cs@cskk.id.au

exit function is indeed different than return statement in function because, proram may continue after exit function has been called in try-except block, but function can never continue after return statement.
I think

return(x)

outside function should immediately end and return x. So it would have same effect as

os._exit(x)

I think one reason people find this awkward is because return is fundamentally not “abort from this unit” (which more what sys.exit() and os._exit() mean) but more like “skip to the end of this execution scope”. A better design of “global return”, if we extend the idea, would be to skip the rest of the module, not exit the program entirely.

1 Like

I concur with @uranusjr. Skipping to the end of the module looks more useful semantic. It could be used in modules which have accelerated implementation:

# Try to import an accelerated implementation
try:
    from _foo import do_something
    return
except ImportError:
    pass

# Fall back to pure Python implementation
def do_something():
    ...

Instead of current

# Pure Python implementation
def do_something():
    ...

# Override with an accelerated implementation
try:
    from _foo import do_something
except ImportError:
    pass

or

# Try to import an accelerated implementation
try:
    from _foo import do_something
except ImportError:
    # Fall back to pure Python implementation
    # (needs additional identation)
    def do_something():
        ...

But, as was noticed by @cameron, it adds a chance that a bug will be left unnoticed.

Tzu-ping Chung,I agree! And keyword import should only add those names from imported module to local scope, that were returned by module, when it was imported. This would replace hidden variable system, because if I do not want some variables to be imported I can just not return these, instead of putting underscore as first character of their name.
But if return is main file not imported file, the return statement should do same as os._exit.