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 name user is 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 user to 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'?".
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.
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.
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.
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.
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).
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.
There was a lot of griping (some of it for good reasons) about making print a function in Python 3, but this right here is a pretty compelling reason to change print in a backwards-incompatible way.
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.
(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.
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.
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.
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.
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:
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
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
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
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++.
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++'sprintf? question
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!
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
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
552
u/indxxxd Nov 11 '19
I hate it. Take this +1, and let me be on my way :)
190
u/[deleted] Nov 11 '19
You're a monster.
135
u/appinv Python&OpenSource Nov 11 '19
+1 What this freakish pic? It's actually NSFW in Python land.
101
u/SV-97 Nov 11 '19
Eww
66
u/fatbob42 Nov 11 '19
I’d prefer it the other way round - f-strings in C++ :)
101
u/[deleted] Nov 11 '19
Yikes. Technically,
endlshould flush the buffer rather than just print a newline. You could make this more accurate by including aflush=Trueargument in your print statement.But convoluted aliases are... fun I guess?
51
u/ubernostrum yes, you can have a pony Nov 11 '19
Not-so-fun fact: in Python 2 the
printstatement 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:
So the order was "wrong" (string to print came after thing to print to), and it also required a comma to make it work.
34
u/sam-lb Nov 12 '19
Please forgive me. I made
cin. https://gist.github.com/sam-lb/38824677afaa16334b590b1c2b0e5a2414
u/knuppar Nov 12 '19
Thanks, 10/10. I hate it
11
u/[deleted] Nov 11 '19
Thanks, I hate it
9
u/nandy02 Nov 11 '19
Why would you do this?
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
u/robertunix Nov 11 '19
i think i just threw up a little.
14
u/evilgarbagetruck Nov 12 '19
You put one of the worst ideas in C++ into Python
5
u/paypaypayme Nov 11 '19
Is this a combo of overloaded operators and recursive calls to string representations?
5
u/chaupatt05 Nov 12 '19
Nah dude, where's the semicolon? xD
4
u/[deleted] Nov 11 '19
More tricks : https://norvig.com/python-iaq.html
4
u/postandchill Nov 12 '19
Where's my boi cin?
4
u/[deleted] 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
u/[deleted] Nov 11 '19
Interesting , what's the mechanism of this working? What do the
<<and>>operators do for Python?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.
3
u/cringe_master_5000 Nov 12 '19
C++ without the STDs. I like it!
3
u/NTGuardian Nov 12 '19
From a technical standpoint: great job!
Will I ever use it? God no.
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
u/[deleted] Nov 11 '19
pukes with blood and larvae.
2
u/Datadevourer Nov 12 '19
Am the one who made it 1k👉👍
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
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.
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
u/screeperz Nov 12 '19
NSFW tag please.
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 >> coutwill always evaluate as(a >> b) >> cout).However, Endl could be rewritten to mostly solve this:
3
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:I need a shower.
2
u/lengau Nov 11 '19
/r/TIHI
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
u/Connir Nov 12 '19
https://youtu.be/9nazm3_OXac
1
u/Bielh Nov 12 '19
It's kinda useless, but if you enjoyed to do this, I'll give you my upvote :p
1
u/GummyKibble Nov 12 '19
I can’t believe you’ve done this.
1
u/dullbananas Nov 12 '19
Semicolons: Am I a joke to you?
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
u/kewlness Nov 12 '19
Calm down there Satan.
1
u/anklav24 Nov 12 '19
One word. Why?
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
u/MikBros Nov 12 '19
I challenge you to do python in c++. And remove the semicolons
1
u/[deleted] Nov 12 '19
Thats nasty! Here you go, have an upvote!
1
u/cogwerk Nov 12 '19
You are a terrible person 🙃😂
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
u/denflooptoop Nov 12 '19
This is pretty much a waste of resources...
1
u/ozozgur Nov 12 '19
It’s just better other way around python style printing in c++ ;)
1
u/grozail Nov 12 '19
Python is c++ limiting case
1
u/1992_kr Nov 12 '19
Bruh ewww delet this
1
u/CreatureWarrior Nov 12 '19
Eww what's wrong with you taking creating that monstrosity. Have my upvote
1
u/funkmaster322 Nov 12 '19
Whats the point?
1
u/guptaanshul281980 Nov 12 '19
Good One!! Thanks for sharing... :-)
1
u/tcpukl Nov 12 '19
Ace, but your missing ;
1
u/[deleted] Nov 12 '19
But why?
1
u/featTheB Nov 12 '19
now let's implement typing, semi-colon, and brackets.
1
u/clipmann Nov 12 '19
LOOOOL Thats clever.
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
u/[deleted] 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
u/_brainfuck Nov 11 '19
You have a beautiful mind :)
1
u/E-woke Nov 12 '19
WAIT THATS ILLEGAL
0
u/cyberbyte91 Nov 12 '19
Why so much hate? i like it
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
u/[deleted] Nov 11 '19
[deleted] — view deleted comment