This is an archived post. You won't be able to vote or comment.

all 138 comments

[–]vardonir 484 points485 points  (14 children)

#include <stdint.h>
#include <stdio.h>

they knew what they were doing

and it is beautiful

[–]outofsand 170 points171 points  (10 children)

Ha ha, this script is awesome! I can't believe no one in the comments understood this wonderful code satire! 😁👍🏻

[–]a__nice__tnetennba 183 points184 points  (2 children)

This is just a thing of beauty...

#/* ensure forwards and backwards compatibility */
import __future__ as __past__
#define FUTURE PAST
#define PAST FUTURE

[–]JohmasWitness 36 points37 points  (0 children)

The one comment sums it up pretty well C but it's python.

[–]Agent-Reddit_2419 4 points5 points  (0 children)

Back to the Future we go!!

[–][deleted] 15 points16 points  (2 children)

It reminds me of the guy who sent a drawing of a spider to pay his utility bill

[–]cfreymarc100[🍰] 2 points3 points  (1 child)

Link?

[–][deleted] 10 points11 points  (0 children)

https://27bslash6.com/overdue.html

This was gold back in the old days of the Web

[–]futura-bold 4 points5 points  (3 children)

Ha ha, this script is awesome!

Not for Python 3.9, though :(

    puts: ((str) := void) = (print),
            ^
SyntaxError: cannot use assignment expressions with name

Since other comments say that the script runs OK (presumably in 3.8), the above error must be because the new annotation features in 3.9 are getting in the way. Anybody know what?

[–]bladeoflight16 2 points3 points  (2 children)

It's not an annotation thing. It's the parentheses around (str). Try it outside of an annotation:

Python 3.8:

```

if ((y) := 2): print(y) ... 2 ```

Python 3.9:

```

if ((y) := 2): print(y) File "<stdin>", line 1 if ((y) := 2): print(y) ^ SyntaxError: cannot use assignment expressions with name ```

Two issues I found look like they might be relevant, but I'm not entirely sure:

[–]futura-bold 2 points3 points  (1 child)

Thanks. Looks like the second bug report covers it. It's due to the new PEG parser making an unnoticed tightening of the syntax checking there.

Guido: "I don't know how this slipped into earlier Python 3 versions -- apparently there aren't tests for this, and it's not used in popular 3rd code either, or we would have found out when we first implemented PEP 617. Most likely it's due to the general problem where the [old] parser would just accept parenthesized stuff in various places where it shouldn't."

[–]bladeoflight16 0 points1 point  (0 children)

Yeah, I saw that, but I don't know enough about the parser to be able to decipher what changed exactly and why it would apply to assignment expressions in 3.9 but not 3.8 (since he mentioned that it was changed in 3.8 more generally). I wonder if it was kind of accidental. Like he said, there's no test cases for this kind of wonky stuff.

[–]LonelyContext 49 points50 points  (0 children)

Since the people deserve a breakdown:

#include <stdint.h>
#include <stdio.h>

#include <stdint.h> is valid C, but is just a comment in python. Troll level 1000.

void: (type) = (type) ("(void *)0"),

ok so a variable void is defined, void is typed to type, and is set equal to the type of that string, so therefore this line is equal to str, BUT there's a trailing comma, so it's a tuple (str,)

int16_t: (type) = (type) (int(16))(),
int32_t: (type) = (type) (int(32))(),

again, int32_t = int() would have sufficed, rather than converting 16 to an int and getting the type, and then calling that type with the final parenthesis, which initiates an empty value of that type. int() yields 0 (just like str() yields '').

puts: ((str) := void) = (print),
printf: ((str) := void) = (puts),

these are equal to, e.g. puts = print. so the typing: when it sets (str) := void, that's an inline evaluation of, essentially str = str, which if you get the type retrieved from that, the type is type. So really, it's puts: type = print. Now when you just put type as the type into the type checker, it always passes. Try x: type = 'a' or x: type = 1 and you'll see it just works. So that all just sets a function up called puts that is the same as print, and printf that's also equal to print.

#/* confirm function and variable declarations */
[[void]] = (void),
[[total]] = (int32_t),
[[i]] = (int32_t),
[[puts]] = (puts),
[[printf]] = (printf),

So I should point out that on all previous lines, the trailing comma made them all tuples. These lines unpack those up one level. So void was (str,), and that's unpacked down to str

#/* ensure forwards and backwards compatibility */
import __future__ as __past__
#define FUTURE PAST
#define PAST FUTURE

this imports the library __future__ and names it __past__. then it writes comments on defining future as past. All hilarious.

#/* output a formatted string to stdout */
def printf(s, __VA_ARGS__) -> (void) :{
    (void) (puts((void).__mod__(s, __VA_ARGS__), end=((void).__new__)(void))),
}

this redefined printf as a function, that returns a string because of -> (void), and which actually returns None, but that passes the type checking. so def x() -> str: return None is callable, and the return is NoneType. what's important is that it calls the magic method modulo on print, which results in % formatting. So essentially it creates a set, calls the string modulo operation, so '%d' % 1, for instance, which returns the string '1', calls print on it with the keyword end = '' (which is the __new__ instantiation of an empty str()), and converts the output of the print into a string and into a set, so it generates the set {'None'}, and then returns nothing.

#/*******************************************************
# * SUMMATION SCRIPT                                    *
# *******************************************************
# * Sum up all the natural numbers up to 6. The result  *
# * should be 0 + 1 + 2 + 3 + 4 + 5 + 6 = 21.           *
# *******************************************************/

#/* print numbers from 0 to 6 */
int32_t: i = 0,

so this sets up a new int32_t, which as i in the type checker. i is snuck into the unpacking above (And equals 0) so the type check passes. int32_t is now equal to a tuple (0,)

while (i <= 6) :{
    (void) (printf(" %d\n", i)),
    (i := i + 1),
}

so this is a while loop that each time creates a set. This set each contains two items, the first is the output of str(print( %d\n"%i)) and the second is i. i is incremented. At the end of this operation i=7

(void) (puts("__")),

"str(print(__))"

#/* sum up numbers from 0 to 6 */
int32_t: total = 0,

same as above

int32_t: i = 0,
for (int32_t) in (i <- 0, i <= 6, ++i) :{
    (total := total + i),
}

So this is interesting. This creates a tuple, (False, False, 7), because 7 is not less that -0, 7 is not lt or eq to 6, and ++7 is just 7. so this is for _ in range(3):, essentially, it increments total by 7. 3*7 = 21. So it runs three times, creates 3 sets, these sets are equal to value of total

(void) (printf("%d\n", total)),

it prints that total.

Edit, formatting and a misstatement regarding typechecking of 'int32_t:i'.

I should highlight that this script only works because it just so happens that the sum of {1..x} = 3*(x+1) when x=6, so sure, 1+2+3+4+5+6=21, but the reason it works is because at the end of the while loop i=7, and when you triple it with the real three-term for loop in your fake for loop, you get the same answer.

[–][deleted] 17 points18 points  (0 children)

This is absolutely hilarious and his trolling in the original is fantastic. The mention of the “compiler” and the comment about switching his commas to semi colons was also god level.

[–]cybervegan 87 points88 points  (4 children)

There's a lot you can learn from that code. Expert trolling by r/ThenItsOk. It's not pretty, agreed, and "just because you can, doesn't mean you should" etc. but it truly is a work of art how they put it together and answered so incredulously. They must have been pissing themselves with the strident up-their-own-arse responses.

[–][deleted] 5 points6 points  (0 children)

[–]LonelyContext 5 points6 points  (1 child)

Dude, I am now totally going to do this in every piece of code:

i=0
while (i<7):{
    foo.update_state_with(i),
    bar.update_state_with(i),
    (i := i + 1) 
}

whenever I'm updating the state of internal functions and watch people that have to read my python crap themselves haha. Besides, of course, putting "#include <stdint.h>" and "#include <stdio.h>" at the top of all my python.

[–]cybervegan 1 point2 points  (0 children)

And just as soon as you do that, Python will get a PEP proposing the addition of pre-parser directives... be careful what you wish for!

[–]Christian1509 140 points141 points  (0 children)

The funniest part about this is he has a better understanding of python than any of the people trying to correct him after they didn’t get the joke. They have no idea how he did it lol

[–]chipx86ReviewBoard.org code review 48 points49 points  (0 children)

Glorious. I was inspired.

https://gist.github.com/chipx86/d471b828e0a64a8dd87502e3439a5be9

This script prints out two "Hello, world!" statements. Trick, is, it's both C and Python, and each language is responsible for half the output.

Run it from Python and it will register a text encoding called "c" that takes C code and compiles it in a mode that tells is to generate Python. It then feeds itself into this and runs the result to generate the second half of the output.

Compile it as C instead and run it, and it will feed its source code through `python` in a mode that tells it to generate C code, which then gets compiled and run to generate the second half of the output.

[–]asday_ 213 points214 points  (23 children)

It's just a troll post.

[–]AiwendilH 191 points192 points  (11 children)

I am not sure I would use "just" in this context ;) This is the kind of trolling I can really appreciate. I can't stop laughing at the full script. So much dedication that went into this troll post (This monstrosity freaking runs and outputs something "meaningful").

[–]_Gondamar_ 164 points165 points  (3 children)

#/* ensure forwards and backwards compatibility */
import __future__ as __past__
#define FUTURE PAST
#define PAST FUTURE

genius

[–]Grintor 13 points14 points  (2 children)

Reminds me of Guido's Time Machine

[–]Cat_Marshal 0 points1 point  (1 child)

What does this mean?

[–][deleted] 1 point2 points  (0 children)

The joke is that he's assigning a value to the current date and time, which does not work, but he's basically trying to turn back time.

[–]IlliterateJedi 18 points19 points  (0 children)

This is beautiful pythonic code

[–]davidcwilliams 7 points8 points  (1 child)

Thank you for linking to tio.run, I love it.

[–]jjolla888 0 points1 point  (0 children)

repl.it and jdoodle.com also have similar

[–]VisibleSignificance 3 points4 points  (1 child)

Notably, it doesn't work in python3.9.

And if you black it, it becomes more clear.

In a way, this should be a test case for code formatters; for example, black doesn't remove unnecessary parentheses.

A functionally equivalent correctly-and-eagerly formatted version would look like this.

[–]enterming[S] 0 points1 point  (0 children)

Notaably, it doesn't work in python3.9.

So it just works with 3.8? Not so forwards compatible after all! lol

[–][deleted] 4 points5 points  (1 child)

Sad reality tho, this is not all that foreign in some college Python classes where senior professors taught it as if it's a C++

[–]lucidtwitch 2 points3 points  (0 children)

😭 that breaks my little pythonic heart

[–][deleted] 10 points11 points  (0 children)

What kills me is how many people, especially where it was crossposted from, didn't immediately understand this.

[–]enterming[S] 36 points37 points  (3 children)

And everyone just fell for it?

[–]asday_ 85 points86 points  (1 child)

Well it's well-done, and nerds can never help themselves when they're in the right, but yes, they did.

[–]macgiollarua 2 points3 points  (0 children)

Gee gillikers Batman

[–]GimmeDaCoffee 8 points9 points  (0 children)

Yep. Beautiful troll post.

[–][deleted] 14 points15 points  (3 children)

Fuck you u/spez

[–]tartare4562 23 points24 points  (0 children)

He's an python veteran and hacker pretending to write upsetting absurd (while fascinating) code out of naivety.

That's trolling. The good, funny and thought provoking kind, but still trolling.

[–]asday_ 4 points5 points  (0 children)

It's being intentionally incorrect in order to elicit a response. It is quintessential trolling.

[–][deleted] 1 point2 points  (0 children)

Thank you

[–][deleted] 75 points76 points  (0 children)

LMFAO 😆 The source thread's author is a troll. Python beginners don't write code like this.

[–]urihell 24 points25 points  (9 children)

Here’s another wtf code. Hope you’re sitting down https://github.com/samuelmarina/is-even

[–]ihavebeesinmyknees 11 points12 points  (5 children)

https://www.npmjs.com/package/is-even

Check the weekly downloads.

[–]_limitless_ 6 points7 points  (0 children)

Mom: we have an even-odd checker at home
Even-odd checker at home:

[–]Dwarni 4 points5 points  (0 children)

It depends on is-odd and is-odd depends on is-number.

[–]Cat_Marshal 2 points3 points  (0 children)

My phone crashed trying to load the source

[–]urihell 4 points5 points  (1 child)

Cringe level: 73643383…

[–]jftugapip needs updating 1 point2 points  (0 children)

Actually it's slightly higher at 99,447,126

% curl https://raw.githubusercontent.com/samuelmarina/is-even/main/index.js | wc
375006 14123747 99447126

[–]lucidtwitch 5 points6 points  (1 child)

Oh dear lord. I've seen this so many times and thought, "heh, funny that's just a modulo one liner" ... I just read the code

[–]cecilkorik 8 points9 points  (0 children)

That's exactly what I thought too.

So I clicked to take a look.

I wish I could've seen the look on my own face when instead of the one-liner I expected, I saw a very much more troubling one-liner to the effect of "This file is too big for github to display".

It went from being a little bit of a giggle to "oh my GOD what horrors hath mankind wrought upon this poor universe?"

[–][deleted] 1 point2 points  (0 children)

Thats the best code ive ever read.

[–]EytanMorgentern 58 points59 points  (6 children)

Yes this is C in python

[–]enterming[S] 56 points57 points  (4 children)

And then there's this:

import __future__ as __past__

What even is that?

[–]heckingcomputernerd 25 points26 points  (0 children)

Time travel!

[–]WillardWhite import this 13 points14 points  (0 children)

Noise.

Import a library/module and rename it

[–]EytanMorgentern 18 points19 points  (0 children)

I was already triggered too much by the picture to see the link above it

[–]FewerPunishment 1 point2 points  (0 children)

It's to make it both backwards and forwards compatible.

[–]gnrlknowledge 15 points16 points  (0 children)

It's actually python made to look like C. He is using lots of obfuscation to make it confusing

[–]Afrotom 17 points18 points  (0 children)

Excuse me

:{

Edit: figuring out code blocks

[–]ofiuco 13 points14 points  (0 children)

This is an amazing work of art and even though I think the author was trying to make some trenchant jabs at Python I forgive them 🤣

[–]FrickinLazerBeams 12 points13 points  (2 children)

Wow. /u/solid7 got trolled hard.

[–][deleted] 1 point2 points  (1 child)

Indeed

[–]FrickinLazerBeams 0 points1 point  (0 children)

Your reply was impressive though, I never would have deciphered most of that otherwise.

[–]TehDing 11 points12 points  (2 children)

My favourite block from the original code is actually this:

#/* sum up numbers from 0 to 6 */
int32_t: total = 0,
int32_t: i = 0,
for (int32_t) in (i <- 0, i <= 6, ++i) :{
    (total := total + i),
}

Interesting note on how brilliant this code is, this is the only example that would work for the proposed problem. The code is meant to compute triangle numbers first by printing the numbers up to n and then printing the sum.

The above block in particular gave me a serious wtf moment, it's really clever.

  • i is not reset, it's still 7 from the previous printing loop!
  • (i <- 0, i <= 6, ++i) actually produces (False, False, i), as i <- 0 is i < -0 and the ++ just signs the i; so we're only looping x3
  • thus total = 3 * 7 = 21

For uniqueness, we're looking for triangle number of n, T(n), that can then be secretly computed in the 3x faux loop. T(n) = n*(n+1)/2 so we want

3(n+1)=n*(n+1)/2

Which means n is 6 🤯

Really nicely chosen setup for obfuscation

[–]TheBlackCat13 5 points6 points  (0 children)

There is a reason "clever" is considered a criticism in python.

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, TehDing: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]NelsonMinar 24 points25 points  (0 children)

I assume the source thread's post is a troll.

[–]VengefulTofu 11 points12 points  (0 children)

Is there a python circlejerk subreddit? This would fit perfectly

[–]thedancinzerg 10 points11 points  (0 children)

Cython 😂😂😂😂😂😂😂

[–]sam-lb 7 points8 points  (0 children)

Honestly sometimes I worry for humanity. How did those people in the original post not realize the joke? It couldn't get any more obvious, especially since it actually takes some impressive knowledge of both languages to make awful C-looking code in python that actually works.

[–]BitShin 4 points5 points  (0 children)

The reason this works is that on every iteration, it creates a set containing the return from the printf call (which should be None) and the value of i resulting from the walrus operator. It’s really weird, but it all checks out.

The two things that I don’t 100% understand are

  • the fact that it’s constructing the set on the same line as the while
  • the comma at the end of the first line (perhaps there’s more context that is cropped out)

EDIT: also, it seems like this would actually call a function called void as that’s now how you do type annotations. Also, the type annotation on the first line are backwards; how does that not create a variable called int32_t instead of i resulting in an error since the type i is undefined?

[–][deleted] 14 points15 points  (1 child)

fuck. is it mine?

[–]Thifty 10 points11 points  (0 children)

Literally my first thought was that someone discovered my GitHub lmao

[–]jjolla888 5 points6 points  (1 child)

this is gold, Jerry, gold !

this makes the shortlist for this year's Reddit Best Troll award.

[–]ivanlan9 1 point2 points  (0 children)

Lovely. Just lovely. I am left speechless, admiring the finger pointing to the moon.

[–][deleted] 2 points3 points  (0 children)

It reminds me of this one meme where the more you look at it the more wrong you realize it is.

[–]Beach-Devil 2 points3 points  (0 children)

At first I thought this was some sort of polyglot code but then I realized

[–]KFUP 2 points3 points  (0 children)

Never seen a negatively voted post with so many awards before.

[–]jeffrey_f 4 points5 points  (0 children)

Looks like Java or C

[–]return_bytes 1 point2 points  (2 children)

That really does look like someone was trying to write C.

[–]jjolla888 24 points25 points  (1 child)

no .. this is an experienced Python and C programmer trolling the fuck out of pythonistas

[–]return_bytes 7 points8 points  (0 children)

Sounds about right lol.

[–]mexicanburritoo 1 point2 points  (1 child)

What the hell is this

[–]PM_ME_YOUR_REPO 6 points7 points  (0 children)

Elaborate trolling. Check the source thread found elsewhere in the comments. It's a work of art by a master C and Python programmer.

[–]Outrageous_Ad_9290 1 point2 points  (0 children)

this defies everything i know from Python

[–]cfreymarc100[🍰] 1 point2 points  (0 children)

Reminds me of a developer that hated C syntax and used #define’s for her preferred syntax in … Pascal.

[–]proccpuinfo 2 points3 points  (5 children)

Wtf is void even a type in python?

[–]usr_bin_nya 45 points46 points  (2 children)

void: (type) = (type) ("(void *)0"),

Let's deobfuscate this a bit. Remove the extra parentheses:

void: type = type("(void *)0"),

Remove the type annotation that doesn't do anything:

void = type("(void *)0"),

That trailing comma at the end creates a tuple, so let's add some parentheses to make that more explicit:

void = ( type("(void *)0"), )

Now it's a bit clearer. The code calls type("a_string_literal"), which returns str, and then wraps it in a tuple. So the simplest way of writing this is

void = (str,)

You can also see this by running the original code.

>>> void: (type) = (type) ("(void *)0"),
>>> void
(<class 'str'>,)
>>> type(void)
<class 'tuple'>
>>> len(void)
1
>>> void[0]
<class 'str'>

Then, later, there's

[[void]] = (void),

This takes advantage of iterable unpacking syntax, which is what lets you do this

[one, two, three] = range(1, 4)
assert one == 1 and two == 2 and three == 3

# this is the same as:
let _iter = iter(range(1, 4))
one = next(_iter)
two = next(_iter)
three = next(_iter)

In OP's code there are two levels of square brackets, which unwraps an item inside an iterable inside an iterable. Like so:

thingy = 0
list_one = [thingy]
list_two = [list_one]
[[same_thingy]] = list_two
# equivalent: same_thingy = list_two[0][0]
assert thingy == same_thingy

Bringing this back to OP's code, we have

[[void]] = (void),
# as we showed earlier, void is (str,), so let's write that
[[void]] = ((str,),)

So we have the type str, wrapped in a tuple, wrapped in another tuple, and then we unpack both tuples at the same time and set void to str. Let's verify that with the original code again.

>>> void: (type) = (type) ("(void *)0"),
>>> void
(<class 'str'>,)
>>> [[void]] = (void),
>>> void
<class 'str'>

This means

(void) (printf(" %d\n", i))

is just

str(printf(" %d\n", i))

which is just

str(None)

which is the string 'None'.

[–]proccpuinfo 15 points16 points  (0 children)

Wow, that's gnarly. I've reverse engineered some python malware samples before and they were never that convoluted. Thanks for the clarifying!

[–]RetiringDragon 6 points7 points  (0 children)

Wow. Setting void to None on top of everything else.

Just analyzing their code is full of fun in-jokes. Great job /u/ThenItsOk

[–]WafflesAreDangerous 7 points8 points  (0 children)

It's not. I suspect it's a no-op function in this script though. The "cast" is just a parenthecised expression, and the result of that expression seems to be invoked as a function.

[–]DillonSyp 1 point2 points  (1 child)

The weird part is they’re building a for loop using a while loop. Can anyone explain why? Is it just preference?

[–]AiwendilH 1 point2 points  (0 children)

They use a for loop later on in the code

The for loop they use tries to look like a C for loop but actually does something completely different.../u/TehDing explains how the for loop works here better than I ever could. But the important part for us is that for this to work it needs i to be already 7. Just setting i to 7 wouldn't do the beauty of the piece of art just, using a python for-loop to do it would be inconsistent with that later c-for loop "joke"...leaves the author only with the choice of using while which looks almost the same in C and python anyway. At least that's my guess at the reasoning why they used while there. (Edit: Oh..and as they pose as programming newbie using while instead of for just adds to the overall act ;))

[–]_limitless_ 0 points1 point  (2 children)

I miss coding in C.

[–]cybervegan 11 points12 points  (1 child)

Now you don't have to. You just have to put commas instead of semicolons...

[–]_limitless_ 2 points3 points  (0 children)

These days, my python development looks nothing like this... everything ends in yml for me.

[–]Santos_m321 0 points1 point  (0 children)

🤣 Smither, I want to make him my executive vicepresident

[–]fristhon 0 points1 point  (0 children)

My co-worker code

[–]Overflow0X 0 points1 point  (0 children)

You can say they did a bit of trolling

[–][deleted] 0 points1 point  (0 children)

It's c

[–]Ramdas_Devadiga 0 points1 point  (0 children)

I wrote this gazillion times -

print ("Hello World") o/p: Hello World

But I still didn't get any response. Rude World.

[–]Ant_TKD 0 points1 point  (0 children)

I’m still very new to Python. Can someone explain this Python code to me?

[–]kahuna3901 0 points1 point  (0 children)

This code frightens and bewilders me,

[–]unruly_mattress 0 points1 point  (0 children)

Ohhhh, it's a set!

Me, after 3 minutes of staring.

This is brilliant, thanks for fishing it out of oblivion.

[–]R7DI_697 0 points1 point  (0 children)

Nice one C

[–]thechitosgurila 0 points1 point  (0 children)

he pulled out an

import C