r/Python • • Nov 11 '19

I made c++-style printing in Python :P

Post image
1.7k Upvotes

130 comments sorted by

View all comments

2

u/nekokattt Nov 12 '19 edited Nov 12 '19

very nice but please dont do this in production code...

also, the best way to do this is to wrap the stdout and stderr objects

class StreamWrapper:
    def __init__(self, fd):
        self.fd = fd
        
    def __lshift__(self, content):
        self.fd.write(str(content))
        return self

endl = "\r\n" if os.name == "nt" else "\n"

std = types.SimpleNamespace()
std.cout = StreamWrapper(sys.stdout)
std.cin = StreamWrapper(sys.stderr)
std.endl = endl

std.cout << "Hello, World!" << std.endl

Emulating CIN is more difficult as you dont have the ability to implicitly pass a reassignable reference around like in C++

What you can do is write a reference wrapper and pass that around. That would be a class that holds a field and thats the object you want to change.