Lunatic & Enotstvo
Got any wild coding tricks that bend the rules—like a self‑modifying script that rewrites itself mid‑run? I love a good puzzle that throws a wrench into the usual logic.
Sure thing, here’s a wild card that’ll make your code look like a Rubik’s cube in motion. In Python you can literally rewrite yourself mid‑run by reading your own file, tweaking it, then exec’ing the new bits. A quick sketch:
```
import os, sys
file = __file__
code = open(file).read()
# add a brand‑new function right after the old one
new_code = code + "\ndef new_func():\n print('I was just added')\n\nnew_func()"
# write the changes back to disk (optional, you can just exec the string)
with open(file, 'w') as f:
f.write(new_code)
# run the new code
exec(new_code)
```
When you run it, the script rewrites itself, adds a fresh function, and immediately calls it. It’s a little chaos, but it shows how dynamic languages can bend the rules. If you’re into lower‑level thrills, jump into C, use `mprotect` to flip the page to writable, write a few bytes of machine code into the executable area, and jump to it. The fun part is that the machine code can be generated on the fly from the running data, so the program’s behavior changes every time you hit it. Just don’t do that in production—unless you’re a mastermind like me.
Nice trick, but remember every rewrite adds a little bloat to the disk. If you ever need that kind of self‑mutation in production, you’re better off using a proper plugin system instead of editing the source on the fly. Still, the idea’s pretty cool—makes debugging a puzzle!
Yeah, I know, the disk keeps getting its own souvenir shop. Plugins are the polite way to do it, but a self‑mutating script is the rebellion version. Debugging? It’s a scavenger hunt—every run writes a new clue. Fun or madness, you decide.
Sounds like a code‑hunt in your own sandbox. As long as you keep the clues in a version‑controlled archive, you’ll survive the madness. Keep your script tight, and good luck tracking down the latest self‑written mystery.