Im adding this just for fun (and to elaborate on my comment). You can take the hacky decorator approach from the second answer from here. For completeness:
class ReturnValue(Exception): def __init__(self, value): Exception.__init__(self) self.value = value def enable_ret(func): def decorated_func(*args, **kwargs): try: return func(*args, **kwargs) except ReturnValue as exc: return exc.value return decorated_func def ret(value): raise ReturnValue(value)
Now, remember that if and while blocks are exceptions in the scoping rules. Specifically, variables defined within an if or while block are available in the scope of the function. If I understood your question correctly, you could now use this like so:
@enable_ret def testfunc(x): # Return None if y is false ret(None) if not (y := x) else 0 # Otherwise we continue (and can access y) here print(y) return 1
Please dont do this though :)
:=operator is probably worth looking at.:=.if (x := f(y)) is None: return APPROPRIATE_ERROR. But indeed, that would probably anger the people who have fully embraced Black...