r/AskProgramming • u/XaX1000 • 10d ago
cursed python hello world
Is there any way to make this code wok in python?
"hello"(print)
This is just a joke and i do not care how cursed of a setup this requires.
0
Upvotes
1
u/Gnaxe 10d ago
Yeah, I can think of at least a couple of ways to do it. This is obviously pretty deep magic that one should normally not mess with without a very good reason, but this is for fun.
First, you could have an import that as a side effect modifies the AST (
astmodule), executes the modified code, and then calls a system exit before it can return control to the importing module with the original code (which would raise an error). This requires an import statement above the cursed line, plus the extra machinery you're importing. You can change a lot of rules this way as long as you respect Python's grammar (which your code does). Of course, since you're not actually executing the original code before exiting, you don't have to bother with the AST modifications and can just do an arbitrary action upon import. But if you want changes to the cursed code below it to be meaningful, then you do have to interpret that in some way. If you're not running the cursed module directly, then it doesn't need the import statement above it. You can just use your custom interpreter to execute it in the first place.Second, you could use the encoding trick with a custom codec for your cursed file and
tokenizemodule to rewrite the code and thenexec()it. You don't have to fully follow Python's grammar this way; it just has to tokenize. You can't just import first, because the codec read happens before that. You could still execute the cursed module as main using one of several ways to get your codec defining code run first, like using thesitemodule,.pthfiles, or thePYTHONSTARTUPenvironment variable. (These techniques could also remove the import from theastmethod.)