Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Wherever you go, there you are

Name: Anonymous 2010-09-15 21:57

Q: Can I use C++'s syntax for ostreams: cout << x << y ... ?

You can. If you don't like writing ``print x, y'' then you can try this:
import sys

class ostream:
    def __init__(self, file):
        self.file = file
       
    def __lshift__(self, obj):
        self.file.write(str(obj));
        return self

cout = ostream(sys.stdout)
cerr = ostream(sys.stderr)
nl = '\n'

cout << x << " " << y << nl


This gives you a different syntax, but it doesn't give you a new convention for printing--it just packages up the str convention that already exists in Python. This is similar to the toString() convention in Java. C++ has a very different convention: instead of a canonical way to convert an object to a string, there is a canonical way to print an object to a stream (well, semi-canonical---a lot of C++ code still uses printf). The stream approach is more complicated, but it does have the advantage that if you need to print a really huge object you needn't create a really huge temporary string to do it.

Name: Anonymous 2010-09-16 17:59

>>5
Because idiots are often tempted to do something as demonstrated in the following PyFIOC code snippet to, for example, read a file into a string:

buf = ""
while 1:
  s = f.read(1024)
  buf += s
  if not len(s):
    break


The issue could be fixed in the VM by not copying the strings and only keeping references to its originating parts and only creating an actual new string upon repeated indexed access on it (sort of a lazy evaluation) but, ironically, VM writers are often too lazy to do it :(..

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List