Is this possible in Python?

alainpoint at yahoo.fr alainpoint at yahoo.fr
Mon Mar 13 18:51:11 CET 2006


Kay Schluehr wrote:
> 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

I made some investigation and reached a (partial) solution to my
problem. It is inspired from a cookbook recipe but it only works for
generator expressions.:
import tokenize
import token
def magic_function(s):
	cursor = None   # to be set to the cursor of the connection
	return_type = object    # can be set to dict or list
	_iterating = False # used in next()
	readline = open(s.gi_frame.f_code.co_filename).readline
	first_line = s.gi_frame.f_code.co_firstlineno
	flag = False
	source = ''    # the source code
	for t in
tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline):
		# check all tokens until the last parenthesis is closed
		t_type,t_string,(r_start,c_start),(r_end,c_end),line = t
		t_name = token.tok_name[t_type]
		if r_start == first_line:
			if t_name == 'NAME' and t_string=="magic_function":
				flag = True
				res = t_string
				start = 0 # number of parenthesis
				continue
		if flag:
			source += ' '+t_string
			if t_name == 'OP':
				if t_string=='(':
					start += 1
				elif t_string == ')':
					start -= 1
					if start == 0:
						break
	return source[2:-2]

assert magic_function(i+2 for i in [1,2])=="i+2 for i in [1,2]"
or
print magic_function(i+2 for i in [1,2])

A general solution is possible and i am sure there are people around
that will provide such a solution

Alain




More information about the Python-list mailing list