Skip to content

Instantly share code, notes, and snippets.

@gazwald
Last active May 31, 2024 22:35
Show Gist options
  • Select an option

  • Save gazwald/e05700aefceb63c37d146b00d1450d45 to your computer and use it in GitHub Desktop.

Select an option

Save gazwald/e05700aefceb63c37d146b00d1450d45 to your computer and use it in GitHub Desktop.
Misusing bitwise dunder methods

C++-like cin and cout in Python

Ever miss cin and cout from C++ when using Python? Me either, but here is a naive implementation for intellectual curiosity:

Code

#!/usr/bin/env python
import inspect


def _cin(*_):
    # https://docs.python.org/3/library/inspect.html#the-interpreter-stack
    current_frame = inspect.currentframe()
    calling_frame = inspect.getouterframes(current_frame)[1]
    code = calling_frame.code_context[0]
    variable_name = code.strip().split(">>")[1].strip()

    result = input()

    globals()[variable_name] = result


std = type(
    "std",
    (),
    {
        "cin": type("cin", (), {"__rshift__": _cin})(),
        "cout": type("cout", (), {"__lshift__": lambda *args: print(args[1])})(),
    },
)

greeting = "world"
std.cin >> greeting
std.cout << f"Hello {greeting}"

Output

$ ./horror.py
, why would you do this?
Hello , why would you do this?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment