552
u/indxxxd Nov 11 '19
I hate it. Take this +1, and let me be on my way :)
12
u/germandiago Nov 12 '19
but u can copy paste code from C++ directly. That is a use case
29
2
2
u/Ulysses6 Nov 12 '19
Making copy-pasting code easier is always a good thing! /s
I can see why it might come handy from time to time, though.
190
135
101
66
u/fatbob42 Nov 11 '19
I’d prefer it the other way round - f-strings in C++ :)
16
Nov 11 '19
18
u/Xirious Nov 12 '19
That's like old style .format and not f-strings.
3
u/germandiago Nov 12 '19
f-strings require some kind of reflection, which C++ unfortunately does not support yet.
3
Nov 12 '19
f-strings require some kind of reflection
Could you please elaborate that?
7
u/flubba86 Nov 12 '19 edited Nov 13 '19
When using f-strings, if you want to do variable substitution (Interpolation) you put the variable name into the string, like
f"Hello {user}"where nameuseris the in-scope variable name containing the string to substitute in.The problem is, now the variable name is baked into the f-string. So at runtime the string formatter needs to be able to look up the in-scope variables and find one called
userto substitute it's value in.In Python, that's easy to do because the interpreter keeps track of the variables, what their names are, and what their values are.
But in a compiled language (like C++) it's different. When the compiler turns the source code into machine instructions, variables become just addresses in memory, and variable names don't exist anymore. But the name "user" is still in the format string and is now meaningless.
Introspection is a fancy feature that allows a compiled language to store some of the information about the source file into the compiled executable. As well it embeds mechanisms in the executable for looking up that information. That can include variable names.
So if you wanted to do run-time f-string interpolation in C++, first you'd have to compile with Introspection turned on, then when running, the formatter would have to ask the Introspection mechanism "what is the memory address for the string which in the source code was called 'user'?".
I hope that made sense.
8
u/nosklo Nov 12 '19
The problem is, now the variable name is baked into the f-string. So at runtime the string formatter needs to be able to look up the in-scope variables and find one called user to substitute it's value in.
That is actually wrong. f-strings can only exist in literals so they can be easily emulated using preprocessor macros that just replace them with a normal format command.
2
u/flubba86 Nov 12 '19
Is that what the python implementation does? Does it simply rewrite the f-string as
.format()invocation during a preprocessing step?3
u/robin-gvx Nov 12 '19
The Python basically turns:
def something(): return f'{something.__name__} and {x:5}'into
def something(): return format(something.__name__) + ' and ' + format(x, '5')... except it has specialized opcodes.
dis.dissays:1 0 LOAD_GLOBAL 0 (something) 2 LOAD_ATTR 1 (__name__) 4 FORMAT_VALUE 0 6 LOAD_CONST 1 (' and ') 8 LOAD_GLOBAL 2 (x) 10 LOAD_CONST 2 ('5') 12 FORMAT_VALUE 4 (with format) 14 BUILD_STRING 3 16 RETURN_VALUE3
u/Agoniscool Nov 12 '19
It doesn't require anything that can't be determined at compile-time, I don't think.
1
Nov 12 '19 edited Nov 12 '19
I believe that some magic with macros and VARGS could do the job :P The trick is to use not used character as quotation mark.
Just like in JavaScript. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
1
u/masklinn Nov 12 '19
f-strings require some kind of reflection
No.
0
u/germandiago Nov 13 '19
Yes, even if implemented by the compiler internally. The same way that std::source_location needs reflection, whether you like it or not.
Another topic is that this reflection is or not exposed to the language itself. FWIW, there is no way in which a string can reference a variable in C++, and that will need to know the compile-time context of the code (variables in scope, etc.), no matter what. Of course, this is without macro tricks.
2
101
Nov 11 '19
Yikes. Technically, endl should flush the buffer rather than just print a newline. You could make this more accurate by including a flush=True argument in your print statement.
But convoluted aliases are... fun I guess?
0
Nov 11 '19
[deleted]
5
u/skintigh Nov 12 '19
Even if the end isn't a carriage return? I thought I had issues with it before, but maybe I am thinking sys.stdout.write, it needs a flush.
8
u/gurnec Nov 12 '19
If stdout is the console, output is line-buffered by default. If it's been redirected to something that's not a TTY, or if you're printing to a non-TTY file, it's block-buffered by default.
2
u/skintigh Nov 12 '19
So if I understand you, any time I print, or write to stdout, without a \n I need to flush the (block) buffer to see the output. That seems to fit my experience (mostly on windows, command line programs).
1
u/gurnec Nov 12 '19 edited Nov 12 '19
I'm not claiming to be an expert here, but yes when writing to a TTY or the Windows console you should manually flush it if it doesn't end in a newline and you need it displayed ASAP.
-4
51
u/ubernostrum yes, you can have a pony Nov 11 '19
Not-so-fun fact: in Python 2 the print statement allowed you to use a >> to send its output to any file-like object.
Not quite the same as C++, though, because it worked like this:
import sys
print >> sys.stderr, "This goes to stderr"So the order was "wrong" (string to print came after thing to print to), and it also required a comma to make it work.
11
u/agrif Nov 12 '19
There was a lot of griping (some of it for good reasons) about making
15
u/Zegrento7 Nov 12 '19
print('Stuff', file=sys.stderr)is quite a bit clearer, and the old syntax can replaced automatically with some regex.3
u/masklinn Nov 12 '19
Don’t forget
print >>sys.stderr, “stuff”,(note the trailing comma) which becomes
print(“stuff”, file=sys.stderr, end=‘ ‘)And actually says what it’s doing.
34
u/sam-lb Nov 12 '19
Please forgive me. I made cin. https://gist.github.com/sam-lb/38824677afaa16334b590b1c2b0e5a24
18
u/peterpetermarie Nov 12 '19
The worst bit is the semicolons.
-7
u/sam-lb Nov 12 '19
Believe it or not, I always use semicolons. Since I'm not working for a company or organization, why not? It's one less thing to remember when switching between languages. I also wrote a script that converts other people's code into my style (semicolons and naming conventions) for GitHub.
But I forget sometimes that no one else does that. Maybe it's a bad habit.
19
u/susek1024 Nov 12 '19
I mean you do you.... but dropping the semicolons would make it easier for others to read.
2
u/crazedizzled Nov 12 '19
How does a semi colon at the end of a line make it harder to read?
4
u/susek1024 Nov 13 '19
Extra characters
(Probably more importantly) people aren’t expecting to see a semicolon when they read python. It’s like you’re asking them to understand your code AND understand that you have a quirk when you write Python.
tHis sEntence oNly hAs a sMall cHange. bUt I bEt iTs a lIttle hArder tO rEad.
1
u/crazedizzled Nov 13 '19
Extra characters
At the end of the line. Completely irrelevant.
people aren’t expecting to see a semicolon when they read python.
Again, it's at the end of the line. You can just ignore it. People can read code in JavaScript and php just fine, I don't see how it matters.
tHis sEntence oNly hAs a sMall cHange. bUt I bEt iTs a lIttle hArder tO rEad.
No, not really. :)
14
u/abrazilianinreddit Nov 12 '19
When sharing your code people will complain to no end that it doesn't adhere to PEP 8. If you don't mind that, than fuck it, it's your code. Use 8-units tabs, end lines with \r, put spaces before commas but not after, just go wild.
-1
9
14
11
9
8
u/abrazilianinreddit Nov 12 '19
"They were so preoccupied with whether or not they could, they didn’t stop to think if they should"
11
14
5
u/paypaypayme Nov 11 '19
Is this a combo of overloaded operators and recursive calls to string representations?
5
4
4
4
Nov 12 '19
I would change \n symbol to os.linesep call (you will need to have import os in your code).
On different platforms there are different line separators.
7
Nov 11 '19
Interesting , what's the mechanism of this working? What do the << and >> operators do for Python?
18
u/sam-lb Nov 11 '19
Typically they are bit shifters. OP, however, has created an atrocity by overloading the bit shift operators with different functionality to imitate the c++ stream insertion syntax.
1
Nov 12 '19
Ah, I see. I didn’t know Python supported operator overloading by defining
__lshift__style functions2
0
Nov 11 '19
[deleted]
20
8
u/mooburger resembles an abstract syntax tree Nov 11 '19
except in this case where it's been overridden.
7
u/winowmak3r Nov 12 '19
Science was too busy asking themselves if they could rather than if they should.
I took the EdX Python course and am about to start on C++ next semester. I have a feeling I'm going to have a lot to get used to. I've taken a peak at C++ and Python just looks so much more easier.
4
3
3
3
u/ingframin Nov 12 '19
You were so preoccupied with whether or not you could, you didn't stop to think if you should. (semi cit.)
2
2
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.endlEmulating 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.
2
u/jturp-sc Nov 12 '19
Yeah, but you were so preoccupied with whether or not you could, that you didn't stop to think if you should.
Now, I need to go vomit in a corner somewhere XD
2
3
u/Xsanda Nov 11 '19
Nice! The left-shift variant should work with multiple arguments too, but unfortunately thanks to precedence the right-shift one can’t work for all cases (a >> b >> cout will always evaluate as (a >> b) >> cout).
However, Endl could be rewritten to mostly solve this:
class Endl:
def __init__(self):
self.string = "\n"
def __rshift__(self, other):
self.string = str(other) + self.string
return self
def __str__(self):
return self.string3
u/crazykid080 Nov 12 '19
I am absolutely disgusted by this and I want this to burn in hell. But you also taught me something so thank you!
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 pythonI need a shower.
4
u/sam-lb Nov 12 '19
__rrshift__is a valid magic method too. It defines right bitshift in the case whereselfis 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
1
u/sam-lb Nov 12 '19
Btw, that's an interesting cin solution. I made one as well: https://gist.github.com/sam-lb/38824677afaa16334b590b1c2b0e5a24
1
u/epic_pork Nov 11 '19
You should convert other to string so you can print numbers and floats too, just like C++ does with operator overloading.
1
u/derekbrokeit Nov 12 '19
Am I the only one who is mildly irritated by the size of the indent here? Looks like tabs, ick.
1
1
1
1
u/fizzygalacticus Nov 12 '19
You were so focused on whether or not you could, you didn't think about whether or not you should.
1
1
1
u/sayoojsamuel Nov 12 '19
Why would anyone want this? rn print() is more than what my life can handle.
PS: your pic is desperately missing the semicolon;
1
1
1
1
u/rperanen Nov 12 '19
For old timer like me, C++ iostream not so bad and feels most natural way to handle printing. You can truly isolate nasty little details behind one interface to use and tests things more independently. Days of great cowboy coders are luckily over even on embedded side.
For Python this is mostly an brilliant troll. I salute you for that
1
1
1
1
1
u/CreatureWarrior Nov 12 '19
Eww what's wrong with you taking creating that monstrosity. Have my upvote
1
1
1
1
1
1
1
u/londey Nov 12 '19
You really want argument dependant lookup to make this equivalent. Ironically C++ has actually adopted a Python like formatting library for the up coming C++20 release. https://en.cppreference.com/w/cpp/utility/format
1
Nov 12 '19
Heresy!!!
Oh most glorious prince of the divine army, Saint Guido van Rossom, defend us in this fight of ours against the hostile princes and powers, against those that want to guide the world into the darkness. And with great effort we will free them of the tyranny of the C and its derivative C++.
1
u/quantzzx Nov 12 '19
Reminds me of the question Can I use C++'s syntax for ostreams: cout << x << y ... ? from Peter Norvigs Python IAQ page, http://norvig.com/python-iaq.html. There is also the What if I like C++'s printf? question
1
1
0
0
u/kukoshel69 Nov 12 '19 edited Nov 12 '19
Why is everyone print-screening the code, instead of copy/paste ? Almost in any comment box there are font settings to display the code in a readable mode. Doing that you'll save the internet bandwidth contributing at a sustainable environment, by consuming less energy of the routers/servers carrying your overcharging data and also other guys may use your code simply by copying if they're interested!
-1
u/Switters410 Nov 12 '19 edited Mar 25 '26
This post has been anonymized and its content removed. Redact was the tool used, possibly for privacy protection, limiting AI data access, or security purposes.
cobweb six correct wakeful water whistle cough gaze fine decide
0
195
u/484448444844 Nov 11 '19 edited Nov 12 '19
We are going full circle- Creating high level languages so we can recreate the low levels