473,780 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using generators with format strings

I have a weird request.

I want to be able to say

def myvalues():
while True:
# stuff that determines a new somevalue
yield somevalue

x = "Hello, %s, this is a %s with %s and %s on top of %s" % myvalues()
y = "Yes it's true that %s has way too many %s's" % myvalues()

I was hoping that myvalues() would be iterated over, but instead the
interpreter gives me a "TypeError: not enough arguments for format string"
error. I tried tuple(myvalues( )) and I think that kinda works but of
course myvalues goes into an infinite loop. myvalues will not know before
hand how many times it will be called.

Is there actually a simple way of doing this that I'm overlooking?

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 18 '05 #1
7 1957
The generators are not list-type objects, but iterators. Because the %
operator does not operate on iterators directly (because, presumably, you
may be wanting to print the iterator itself, not the items it iterates
over), you must construct a list out of it, which can be done very easily,
as you can see.

x = "Hello, %s, this is a %s with %s and %s on top of %s" % [ i for i in
myvalues()]
y = "Yes it's true that %s has way too many %s's" % [i for i in myvalues()]

marduk wrote:
I have a weird request.

I want to be able to say

def myvalues():
while True:
# stuff that determines a new somevalue
yield somevalue

x = "Hello, %s, this is a %s with %s and %s on top of %s" % myvalues()
y = "Yes it's true that %s has way too many %s's" % myvalues()

I was hoping that myvalues() would be iterated over, but instead the
interpreter gives me a "TypeError: not enough arguments for format string"
error. I tried tuple(myvalues( )) and I think that kinda works but of
course myvalues goes into an infinite loop. myvalues will not know before
hand how many times it will be called.

Is there actually a simple way of doing this that I'm overlooking?

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet
News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World!
100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total

Privacy via Encryption =---


--
Jul 18 '05 #2

"Calvin Spealman" <ca****@ironfro ggy.com> wrote in message
news:11******** ********@ironfr oggy.com...
The generators are not list-type objects, but iterators. Because the %
operator does not operate on iterators directly (because, presumably, you
may be wanting to print the iterator itself, not the items it iterates
over), you must construct a list out of it, which can be done very easily, as you can see.

x = "Hello, %s, this is a %s with %s and %s on top of %s" % [ i for i in
myvalues()]
y = "Yes it's true that %s has way too many %s's" % [i for i in

myvalues()]

list(myvalues() ) is even more concise and more direct than the list comp

tjr

Jul 18 '05 #3
On Mon, 26 Jul 2004, Calvin Spealman wrote:
The generators are not list-type objects, but iterators. Because the %
operator does not operate on iterators directly (because, presumably, you
may be wanting to print the iterator itself, not the items it iterates
over), you must construct a list out of it, which can be done very easily,
as you can see.


Not quite, because for the same reason as generators, lists are passed to
% as a single argument. The arguments must be contained in a tuple
(tuple(myvalues ()) does nicely).

Jul 18 '05 #4
On Tue, 27 Jul 2004 09:15:57 -0400, Christopher T King <sq******@wpi.e du> wrote:
On Mon, 26 Jul 2004, Calvin Spealman wrote:
The generators are not list-type objects, but iterators. Because the %
operator does not operate on iterators directly (because, presumably, you
may be wanting to print the iterator itself, not the items it iterates
over), you must construct a list out of it, which can be done very easily,
as you can see.


Not quite, because for the same reason as generators, lists are passed to
% as a single argument. The arguments must be contained in a tuple
(tuple(myvalues ()) does nicely).


does anyone else get the feeling that (str %) should have a third
behaviour wrt generators? By this I mean that str % seq is one
behaviour, str % dict is another, and there should be a str % iter,
probably consuming items from the iterator up to the number of
arguments of the format string?

--
John Lenton (jl*****@gmail. com) -- Random fortune:
bash: fortune: command not found
Jul 18 '05 #5
On Tue, 27 Jul 2004, John Lenton wrote:
does anyone else get the feeling that (str %) should have a third
behaviour wrt generators? By this I mean that str % seq is one
behaviour, str % dict is another, and there should be a str % iter,
probably consuming items from the iterator up to the number of
arguments of the format string?


The only argument I see against this is that it could break existing code
of the form '%r' % some_object, where some_object could easily be an
iterable object (say, a numarray array). Of course, limiting it to only
generators rather than iterators in general would fix this, but then the
benefit gained seems too small to justify the cost of implementing another
exception to the rule.

Jul 18 '05 #6
On Wed, 21 Jul 2004 15:21:50 -0500, marduk <ma****@python. net> wrote:
I have a weird request.

I want to be able to say

def myvalues():
while True:
# stuff that determines a new somevalue
yield somevalue

x = "Hello, %s, this is a %s with %s and %s on top of %s" % myvalues()
y = "Yes it's true that %s has way too many %s's" % myvalues()

I was hoping that myvalues() would be iterated over, but instead the
interpreter gives me a "TypeError: not enough arguments for format string"
error. I tried tuple(myvalues( )) and I think that kinda works but of
course myvalues goes into an infinite loop. myvalues will not know before
hand how many times it will be called.

Is there actually a simple way of doing this that I'm overlooking?


If you are willing to modify your format strings so they call on a
mapping (with ignored key '' in this case), you can supply a mapping that will do the job:
def myvalues(): ... values = 'one two three'.split() + [4,5,6]
... while True:
... # stuff that determines somevalue
... for somevalue in values:
... yield somevalue
... mapping = type('',(),{'__ getitem__':lamb da s,k,g=myvalues( ).next:g()})()
x = "Hello, %s, this is a %s with %s and %s on top of %s".replace('%' ,'%()') % mapping
y = "Yes it's true that %s has way too many %s's".replace(' %','%()') % mapping
x 'Hello, one, this is a two with three and 4 on top of 5' y

"Yes it's true that 6 has way too many one's"

You can obviously define mapping as an instance of a more conventionally defined class also,
and pass the generator to its constructor. Maybe even differentiate among multiple keyword-named
generators if you want to feed in several value streams and not ignore keys from the format.

You don't want to use .replace('%','% ()') if your format string already has some '%(...) or
'%%' instances in it, of course.

Hm, maybe if '%s' without mapping names were interpreted as a mapping with an integer key
whose value was the position of the %s in the format, then a mapping could (if it had the
integer key in question, otherwise its __str__ method would be called) be used with ordinary
formats as well. E.g.,

'%s %04x' % mapping

would get mapping[0] and mapping[1] as the values to convert per the format. Note that
that's not equivalent to '%(0)s %(1)04x' which would use keys '0' and '1' instead of 0 and 1.
You could of course make a mapping that would ignore the keys for some purpose, as I did above.
Just a wild idea, don't take too seriously ;-)

Regards,
Bengt Richter
Jul 18 '05 #7
On Tue, 27 Jul 2004 11:28:29 -0400, Christopher T King <sq******@WPI.E DU> wrote:
On Tue, 27 Jul 2004, John Lenton wrote:
does anyone else get the feeling that (str %) should have a third
behaviour wrt generators? By this I mean that str % seq is one
behaviour, str % dict is another, and there should be a str % iter,
probably consuming items from the iterator up to the number of
arguments of the format string?


The only argument I see against this is that it could break existing code
of the form '%r' % some_object, where some_object could easily be an
iterable object (say, a numarray array). Of course, limiting it to only
generators rather than iterators in general would fix this, but then the
benefit gained seems too small to justify the cost of implementing another
exception to the rule.


You could subtype str and override __mod__ to do it (which I'll leave
as an exercise ;-) e.g.,

class MYFMT(str):
def __mod__(self, args):
...

and then use it like

MYFMT('formatte d string args from generator: %s %r %(mapping_key)s ') % generator

Then you could make it do anything you like without changing current python, even
mixing in mapping usage if you wanted to.

Regards,
Bengt Richter
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3789
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 Python script, which would be run in it's entirety and return control to the C++ code. After looking...
3
1953
by: Carlos Ribeiro | last post by:
As a side track of my latest investigations, I began to rely heavily on generators for some stuff where I would previsouly use a more conventional approach. Whenever I need to process a list, I'm tending towards the use of generators. One good example is if I want to print a report, or to work over a list with complex processing for each item. In both cases, a simple list comprehension can't be used. The conventional approach involves...
3
2287
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
11
6600
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on where the job is running, the job runs sucessfully, PDF files got generated, everything is good. If I scheduled the job to run at the time that I am not logged into the server, Access is not able to print to the printer. The error is pretty...
5
2262
by: Just Me | last post by:
Using streams how do I write and then read a set of variables? For example, suppose I want to write into a text file: string1,string2,string3 Then read them later. Suppose I want to write and then read: string1, integer1, double1
3
2078
by: Klint Gore | last post by:
Does anyone know of a mailing list for application developers using postgres? It'd probably be more relevant than pgsql-general for my question. Failing that, what do people use to generate reports with a postgres back end? I have a requirement to produce a reporting daemon on linux that doesn't require X windows (has to render the report and write it back to a blob). I've been down a couple of paths that ended with...
3
2673
by: walterbyrd | last post by:
I would like to put together a very simple inventory program. When I ship an item, and edit the quantity; I would like the quantity _on_hand to auto-decrement, and the quantity_to_reorder to auto-increment. Also, when the data is displayed in a table format, I would like to be able to edit the quantity field as I would in a spreadsheet, just edit that field, without having to change to an edit-record screen. It seems like I should be...
4
1435
by: VMI | last post by:
In the next few weeks, we'll be discussing what standards will be used for our web development, and one of the suggestions was to use a code generator (in our case, the first version of LLBLGen). Personally, I don't like code generators. I inherited two web applications that use LLBLGen, and they are just impossible to debug. It generates so many classes and so much code that isn't actually used. In my case, I'm maintaining web app with...
13
1820
by: Martin Sand Christensen | last post by:
Hi! First a bit of context. Yesterday I spent a lot of time debugging the following method in a rather slim database abstraction layer we've developed: ,---- | def selectColumn(self, table, column, where={}, order_by=, group_by=): | """Performs a SQL select query returning a single column
0
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9931
tracyyun
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
agi2029
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6727
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5373
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
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
3
2869
bsmnconsultancy
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.