August 04, 2004
Extended Print Form
In all of this discussion of function decorators there have been a few mentions of the extended print syntax (>> - also known as print chevron). I've never used it and wondered how useful it would be and, more importantly, how to invoke it.
I could find the language lawyer definition of the syntax, but that's a little tricky and a quick google could find no examples that actually worked. I even looked in the tutorial but came up with nothing either.
It took me a couple of goes, probably because I'm not very good at reading the Python grammar notation, but here is my example;
>>> myFile = file('/tmp/chevron.log', 'w+')
>>> print >> myFile, "A line of text to append to the file"
Update Thanks to Fredrik and Malcolm for pointing out the missing chevrons, they should now be back. I'd also like to point out that I wasn't complaining about the implementation, rather that I couldn't find any examples of how to use it after a superficial search.
Posted by Andy Todd at August 04, 2004 10:16 AM
The last line of your example doesn't include the chevron! It should be
print >> myFile, "A line of text to append to the file"
Speaking as somebody who does Python programming for a living, I have not found myself using this syntax very much since it was introduced into the language. Maybe I'm just weird.
Posted by: Malcolm Tredinnick on August 4, 2004 10:59 AMFootnotes:
Your blogging software ate your chevron.
You can find the original design document (including the rationale) here: http://www.python.org/peps/pep-0214.html
Also note that unlike the @dec fiasco, there was a design spec (which includes an extensive rationale) for the extended print syntax *before* the core distribution was modified. In contrast, the current descriptor PEP (http://www.python.org/peps/pep-0318.html) doesn't even mention @dec as a alternative, nor does it discuss semantics when multiple decorators are used, though the examples imply left-to-right, while the patch implements right-to-left (the last descriptor is applied first). In other words, it's a complete process breakdown.
Posted by: Fredrik on August 4, 2004 11:15 AMI never use print >> as well. It's sure nice to have, I just never use it.
Posted by: Florian Bösch on August 4, 2004 02:42 PMI'd like to know how to use this to apppend to a file rather than overwrite it. (yeah, it might show, so I'll 'fess up. I am a bit newbie)...
I am doing something like this:
for x in i:
bleh = open(r'myFile', w+')
print >> bleh, x
sort1.close()
where i is a list. This ends up producing a file with the final iteration.
Nemir, to append to a file you use the 'a' switch when opening it. I would also only open it once. So in your example would become something like;
bleh = open(r'myFile', 'a')
for x in i:
print >> bleh, x
bleh.close()