Can Python Be Forced to Run “hello”(print)?

0
2
Asked By MellowCactus42 On

Is there any way to make this deliberately cursed expression work in Python?

"hello"(print)

This is purely a joke, so solutions involving unsafe hacks, monkey-patching, or other ridiculous setup are completely welcome.

3 Answers

Answered By BreezyLantern24 On

The core obstacle is that Python's call syntax is implemented by the object's type. Normally, str objects are not callable, so you cannot simply define an operator overload in regular Python. You would need to alter the type itself or patch the interpreter, which is why the clean solution is just print("hello") and the cursed solutions involve unsupported hacks.

Answered By VelvetOrchid7 On

One experimental approach is to use a library such as forbiddenfruit to add a custom __call__ method to str. The idea is that calling a string would pass the string itself to the function supplied as the argument, making "hello"(print) behave roughly like print("hello"). However, this relies on modifying built-in types and may not work reliably across Python versions.

CopperFable19 -

That sounds like a joke, but the library really does attempt this kind of built-in modification. It still isn't guaranteed to work, though.

QuietNimbus53 -

In practice, this approach can fail depending on the interpreter and Python version, so it is more of a curiosity than a dependable solution.

Answered By QuartzWanderer8 On

A much more dangerous option is using ctypes to overwrite part of the built-in str type's internal function table. A custom C-compatible callback could receive the string and the function argument, then invoke the function with the string. This is interpreter-specific, extremely unsafe, and could crash Python or corrupt memory, but it demonstrates how the expression might be forced to work.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.