Context-aware return
Mark Lawrence
breamoreboy at yahoo.co.uk
Fri Sep 11 22:11:50 EDT 2015
On 10/09/2015 18:54, Steven D'Aprano wrote:
> I have a function which is intended for use at the interactive interpreter,
> but may sometimes be used non-interactively. I wish to change it's output
> depending on the context of how it is being called.
>
> If the function is being called as if it were a procedure or command, that
> is the return result is just ignored, I want to return one thing. But if it
> is being called where the return result goes somewhere, I want to return
> something else. Most importantly, I don't want to pass a flag to the
> function myself, I want the function to know its own context.
>
> I don't mind if it is CPython only, or if it is a bit expensive.
>
> E.g.
>
> def func():
> do_stuff()
> if procedure: # FIXME what goes here???
> return "Awesome"
> else:
> return 999
>
> Now I can do this:
>
> x = func()
> assert x == 999
>
> L = [1, 2, func(), 4]
> assert L[2] == 999
>
> func()
> # interactive interpreter prints "Awesome"
>
> Is such a thing possible, and if so, how would I do it?
>
> If I did this thing, would people follow me down the street booing and
> jeering and throwing things at me?
>
Not unless you were thrown in the Australian equivalent of Broadmoor
first. For those who don't know, Broadmoor is a famous place in the UK
for the criminally insane.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Python-list
mailing list