Is this possible in Python?

Kay Schluehr kay.schluehr at gmx.net
Mon Mar 13 04:31:48 EST 2006


alainpoint at yahoo.fr wrote:
> Hi
>
> I wonder if Python is capable of the following: define a function which
> returns its argument.
> I mean:
> def magic_function(arg):
>         ...... some magic code ...
>
> that behaves the following way:
>
> assert magic_function(3+4)=="3+4"
> assert magic_function([i for i in range(10)])=="i for i in range(10)]"
>
> It is not trivial at all and might require some bytecode hacking that i
> am unable to do myself BUT you are the experts ;-)
>
> Alain

Storing arguments away before they are evaluated doesn't work in
Python. You have to hack the compiler in order to access the parsetree.
You might take a look at the compiler package of the standard library
that enables access to ASTs. Thus you could define lazy evaluation and
just-in-time compilation of some particular ASTs. I do not recommend
doing this for real purposes, but it is a good excercise and sooner or
later you become an expert yourself :)

Kay




More information about the Python-list mailing list