Hello,
I was playing around a bit with generators using next() and send(). And
I was wondering why an extra send() method was introduced instead of
simply allowing an argument for next().
Also, I find it a bit counter-intuitive that send(42) not only "sets"
the generator to the specified value, but yields the next value at the
same time.
As an exercise, I wanted to somehow "modify" a generator so that it
would have a next() method accepting an argument, something like
@myway
def gen():
pass
But I failed to come up with an implementation of the myway() function.
Any comments and/or suggestions?
Greetings,
Thomas
--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche) 7 2868
Thomas Mlynarczyk <th****@mlynarc zyk-webdesign.dewri tes:
Hello,
I was playing around a bit with generators using next() and
send(). And I was wondering why an extra send() method was introduced
instead of simply allowing an argument for next().
Also, I find it a bit counter-intuitive that send(42) not only "sets"
the generator to the specified value, but yields the next value at the
same time.
If you want to simply 'set' the generator (by which I take you mean
'change its state') without without iterating it one step, then what you
need is a class with an __iter__() method. Then you can change the
state of the object between calls to next(). E.g.
>>class MyGenerator(obj ect):
.... def __init__(self, v): self.v = v
.... def __iter__(self):
.... for x in range(10):
.... yield self.v
....
>>g = MyGenerator(5) for i in g:
.... g.v = input("val:")
.... print i
....
val:4
5
val:10
4
val:34
10
val:56
34
val:
Etc...
--
Arnaud
Arnaud Delobelle schrieb:
If you want to simply 'set' the generator (by which I take you mean
'change its state') without without iterating it one step, then what you
need is a class with an __iter__() method. Then you can change the
state of the object between calls to next(). E.g.
>>>class MyGenerator(obj ect):
... def __init__(self, v): self.v = v
... def __iter__(self):
... for x in range(10):
... yield self.v
...
>>>g = MyGenerator(5) for i in g:
... g.v = input("val:")
... print i
That's a good idea, thanks! Meanwhile I have succeeded in writing a
decorator which allows an argument for next():
def myway( g ):
class mygen( object ):
def __init__( self, n ):
self.g = g( n )
def __iter__( self ):
return self
def next( self, s = None ):
return self.g.next() if s is None else self.g.send( s )
def send( self, s ):
return self.g.send( s )
return mygen
@myway
def gen( n ):
i = 0
while i <= n:
s = yield i
if s is not None:
i = s
else:
i += 1
Of course, this is just an exercise -- it doesn't look as if it's worth
using @mayway in any "real" code just to be able to write g.next(42)
instead of g.send(42). Still, I would like to know why it was decided to
introduce a send() method instead of allowing an argument for next().
Thanks and greetings,
Thomas
--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
On Nov 17, 7:36*am, Thomas Mlynarczyk <tho...@mlynarc zyk-webdesign.de>
wrote:
Still, I would like to know why it was decided to
introduce a send() method instead of allowing an argument for next().
Hey Thomas,
A great place to gain insight into the reasoning behind changes to
Python is the PEPs: http://www.python.org/dev/peps/pep-0342/
That links to the original proposal to extend the generator behaviour
to include send. I haven't the time right now to read it but if
anything is going to explain the choice, it'll be there.
At a guess, I'd expect a new method was chosen to provide semantic
distinctness with the original behaviour. Or maybe so it wouldn't
break any existing code with decorators such as your's :)
On Nov 16, 3:36*pm, Thomas Mlynarczyk <tho...@mlynarc zyk-webdesign.de>
wrote:
Arnaud Delobelle schrieb:
If you want to simply 'set' the generator (by which I take you mean
'change its state') without without iterating it one step, then what you
need is a class with an __iter__() method. *Then you can change the
state of the object between calls to next(). *E.g.
>>class MyGenerator(obj ect):
... * * def __init__(self, v): self.v = v
... * * def __iter__(self):
... * * * * for x in range(10):
... * * * * * * yield self.v
...
>>g = MyGenerator(5) for i in g:
... * * g.v = input("val:")
... * * print i
That's a good idea, thanks! Meanwhile I have succeeded in writing a
decorator which allows an argument for next():
Here's a different structure if you want it. Untested.
def myway( g ):
def init( *ar, **kw ):
g= g( *ar, **kw )
* * *class mygen( object ):
* * * * *def __iter__( self ):
* * * * * * *return self
* * * * *def next( self, s= None ):
* * * * * * *return g.next() if s is None else g.send( s )
* * * * *def send( self, s ):
* * * * * * *return g.send( s )
* * *return mygen
return init
And, if you don't intend to use 'myway' on 'listiterator's and such,
'send( None )' is equivalent to 'next( )'.
def myway( g ):
def init( *ar, **kw ):
g= g( *ar, **kw )
class mygen( object ):
def __iter__( self ):
return self
def next( self, s= None ):
return g.send( s )
def send( self, s ):
return g.send( s )
return mygen
return init
There's probably a typo in it.
alex23 schrieb: http://www.python.org/dev/peps/pep-0342/
That links to the original proposal to extend the generator behaviour
After some searching, I found this as a remark in parentheses:
"Introducin g a new method instead of overloading next() minimizes
overhead for simple next() calls."
And also a (little) more detailed explanation. So, basically, allowing
an argument for next() would have meant more overhead in the Python
implementation. Still, I don't quite see why, as this could be detected
at compile time, couldn't it?
On the other hand, if I understood correctly, I can use send(None) as an
equivalent of next(). So, while I cannot have next(argument) instead of
send(argument), I can have send(None) instead of next().
At a guess, I'd expect a new method was chosen to provide semantic
distinctness with the original behaviour.
But the semantics would not have changed, they would only be "extended"
and thus remain "compatible ", wouldn't they?
Greetings,
Thomas
--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
Aaron Brady schrieb:
And, if you don't intend to use 'myway' on 'listiterator's and such,
'send( None )' is equivalent to 'next( )'.
I didn't know that. But doesn't that impose a restriction somehow? It
makes it impossible to send a None to a generator.
Greetings,
Thomas
--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
On Nov 18, 5:20*pm, Thomas Mlynarczyk <tho...@mlynarc zyk-webdesign.de>
wrote:
Aaron Brady schrieb:
And, if you don't intend to use 'myway' on 'listiterator's and such,
'send( None )' is equivalent to 'next( )'.
I didn't know that. But doesn't that impose a restriction somehow? It
makes it impossible to send a None to a generator.
No, None is a valid value to use with send. Not all iterators support
send. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Francis Avila |
last post by:
Below is an implementation a 'flattening' recursive generator (take a nested
iterator and remove all its nesting). Is this possibly general and useful
enough to be included in itertools? (I know *I* wanted something like it...)
Very basic examples:
>>> rl = , '678', 9]]
>>> list(flatten(rl))
>>> notstring = lambda obj: not...
|
by: Francis Avila |
last post by:
A little annoyed one day that I couldn't use the statefulness of
generators as "resumable functions", I came across Hettinger's PEP 288
(http://www.python.org/peps/pep-0288.html, still listed as open, even
though it's at least a year old and Guido doesn't seem very hot on the
idea). I'm not too sure of its ideas on raising exceptions in...
|
by: The_Incubator |
last post by:
As the subject suggests, I am interested in using Python as a scripting
language for a game that is primarily implemented in C++, and I am also
interested in using generators in those scripts...
Initially I was justing looking at using Python for some event
scripting. So basically an event would trigger an object to run the
appropriate...
|
by: fishboy |
last post by:
Howdy,
I'm in middle of a personal project. Eventually it will download
multipart binary attachments and look for missing parts on other
servers. And so far I've got it to walk a newsgroup and download and
decode single part binaries.
I thought I'd post the code and see what people think. I'd appreciate
any feedback. It's my first...
|
by: fishboy |
last post by:
Howdy,
Sorry if this is a double post. First try seemed to go into
hyperspace.
I'm working on a personal project. It's going to be a multipart
binary attachment downloader that will search alternate servers for
missing pieces. This is the working code so far. It will walk a
newsgroup and download and decode all the single part...
| |
by: Jordan Rastrick |
last post by:
First, a disclaimer. I am a second year Maths and Computer Science
undergraduate, and this is my first time ever on Usenet (I guess I'm
part of the http generation). On top of that, I have been using Python
for a grand total of about a fortnight now. Hence, I apologise if what
follows is a stupid suggestion, or if its already been made...
|
by: Michael Sparks |
last post by:
Hi,
I'm posting a link to this since I hope it's of interest to people here :)
I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework,
and it's been published as a BBC R&D White Paper and is available here:
* http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml
|
by: Andrew Koenig |
last post by:
Can anyone think of an easy technique for creating an object that acts like
a generator but has additional methods?
For example, it might be nice to be able to iterate through an associative
container without having to index it for each element. Right now, I can say
i = iter(d)
and then repeatedly calling i.next() gives us the keys for...
|
by: Ben Sizer |
last post by:
A simple question - can anybody give a short example of how these work
and what they are good for? I've read PEP 342 and the associated bit in
the What's New section and it's still all Greek to me. The latter seems
to focus on how to do it, rather than why you'd do it, so it doesn't
aid the understanding too much.
--
Ben Sizer
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
| |
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |