[Python-ideas] How can I get own instance of generator in itself code
Alexandre Zani
alexandre.zani at gmail.com
Sun Jul 15 17:58:10 CEST 2012
On Sat, Jul 14, 2012 at 11:18 PM, Đinh Nho Nam <namdn at socbay.com> wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
I would suggest creating a decorator for this:
def self_decorator(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
return f(f, *args, **kwargs)
@self_decorator
def do_stuff(self, a, b, c):
pass
Should work for any kind of function.
And C/C++ do support such functionality in the sense that you can keep
state in between function invocations:
// This will return 1 the first time it is called, 2, the next time and so on...
int generator() {
static int num = 0;
num += 1;
return num;
}
On a final note, this question more appropriate for python-list.
python-ideas is for the discussion of ideas to change python itself.
Alex
More information about the Python-ideas
mailing list