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/random_cynic Nov 12 '19

It's been a while since I programmed regularly in C++, but I thought the right shift operator is for input (stream insertion). Also the python function for right shift is __rshift__() not __rrshift__(). It would be hard to do input like in C++ but since we are playing code golf:

class Cppio:
    def __lshift__(self, other):
        print(other, end="")
        return self
    def __rshift__(self, var):
        var.append(input())
        return self

class Endl:
    def __str__(self):
        return "\n"

class Mylist(list):
    def __repr__(self):
        return self[0]

cout = Cppio()
cin = Cppio()
endl = Endl()
somevar = Mylist()

cout << "C++ printing in python" << endl
cin >> somevar
cout << somevar << endl

$ python cout.py                                  
C++ printing in python
C++ input in python
C++ input in python

I need a shower.

4

u/sam-lb Nov 12 '19

__rrshift__ is a valid magic method too. It defines right bitshift in the case where self is the right operand.

2

u/random_cynic Nov 12 '19

Wow, you're right, TIL. Well at least some good came of this :P.

1

u/sam-lb Nov 12 '19

Lol, yeah.