Is this possible in Python?

S

Steven D'Aprano

Kay said:
jalanb wrote:
You might like the version here:
http://www.jorendorff.com/toys/out.html

Especially the "need to know" presentation, which is cute

--
Alan
http://aivipi.blogspot.com

Thank you for the tip.
Meanwhile, I found a shorter solution to my problem:
def magic(arg):
import inspect
return inspect.stack()[1][4][0].split("magic")[-1][1:-1]

assert magic(3+4)=="3+4"

Alain

Does it? Using your function I keep an assertion error. Storing the
return value of magic()in a variable s I receive the following result:

def magic(arg):
import inspect
return inspect.stack()[1][4][0].split("magic")[-1][1:-1]

s = magic(3+4) # magic line
'lin'


BTW grepping the stack will likely cause context sensitive results.

Kay


This is no production-ready code, just a proof of concept.
Adding 3 or 4 lines would make it more robust.
Just hope someone else will benefit from this discussion.

Doesn't work for me either:
.... import inspect
.... return inspect.stack()[1][4][0].split("magic")[-1][1:-1]
....Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in magic
TypeError: unsubscriptable object


Kay gets an AssertionError, I get a TypeError. I think describing it as
"proof of concept" is rather optimistic.

Here is the inspect.stack() I get:

[(<frame object at 0x825d974>, '<stdin>', 2, 'magic', None, None),
(<frame object at 0x8256534>, '<stdin>', 1, '?', None, None)]
 
A

alainpoint

Steven said:
Doesn't work for me either:
... import inspect
... return inspect.stack()[1][4][0].split("magic")[-1][1:-1]
...Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in magic
TypeError: unsubscriptable object


Kay gets an AssertionError, I get a TypeError. I think describing it as
"proof of concept" is rather optimistic.

Here is the inspect.stack() I get:

[(<frame object at 0x825d974>, '<stdin>', 2, 'magic', None, None),
(<frame object at 0x8256534>, '<stdin>', 1, '?', None, None)]

You just proved what i was saying: this is no robust code. It
apparently does not work from the command line. It has problems with
comments on the same line. It might have problems with multi-line
arguments, etc ....
Please feel free to improve the above function and make it robust.
(meanwhile, i removed the SOLUTION FOUND from the subject title, until
you come up with such a robust version ;-))
Alain
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,290
Messages
2,571,453
Members
48,129
Latest member
DianneCarn

Latest Threads

Top