[Python-ideas] How can I get own instance of generator in itself code

Đinh Nho Nam namdn at socbay.com
Sun Jul 15 08:18:59 CEST 2012


Hi Python Software Foundation!
I have learned Python for 2 years, and I love this language very much. The structure and grammar are simple and beautiful. I used this language in most of my projects.
Now, I learn to use generator. This architecture is very intelligent. It allows programmer can pause and resume function. I think that this feature is not supported in classic language as C++, Java, C#.. In my design, we use 1 generator in both tasks: invoke and callback when download one url. But I have a small problem when getting instance of generator. How can I get own instance of generator in itself code? 
detail pseudo code example:

def invoke_callback(url):
	do something here
	self = get myself (invoke_callback generator) instance #how can we do as this line????
	data = yield asynchronous_dowload(url, callback = self.next)
	do something with data

How can we do as this code. How can I get self variable?. Does the language support this feature? I cannot find it in any document in python.org. So, I have to solve it by wrapper it in a list.

def invoke_callback(url, wrapper):
	self = wrapper[0]
	data = yield asynchronous_dowload(url, callback = self.next)
	do something with data

wrapper = []
instance = invoke_callback(url, wrapper)
wrapper.append(instance)
instance.next()

The other way is sending instance to itself, and we invoke twice.

def invoke_callback(url):
	self = yield
	data = yield asynchronous_dowload(url, callback = self.next)
	do something with data
instance = invoke_callback(url)
instance.next()	#first
instance.send(instance)	#second

But the code in both of ways is not nice. Can you add this feature in the next version of python???
Regards
Namdn



More information about the Python-ideas mailing list