Magic Methods and Metaprogramming

Trigger paths of __get/__set/__call/__toString/__invoke, beside Python dunders, JS Proxy and Rust traits as metaprogramming entries.

C C23

C23
#include <stdio.h>

/* C has no magic: a function-pointer table IS the dispatch mechanism */
typedef struct {
    const char *(*greet)(const char *);
} Box;

static const char *box_greet(const char *who) {
    static char buf[64];
    snprintf(buf, sizeof(buf), "called greet(%s)", who);
    return buf;
}

int main(void) {
    Box b = {box_greet}; /* wiring is explicit, at construction */
    printf("%s\n", b.greet("hi"));
    return 0;
}
Output
called greet(hi)

C++ C++26

C++26
#include <cstdio>
#include <string>

// C++'s closest "magic": operator overloading — the call site looks like
// built-in syntax but dispatches statically at compile time
class Box {
public:
    std::string color = "red";
};

static std::string operator*(const Box &b, int n) { // Box * n : repeat the color
    std::string out;
    for (int i = 0; i < n; ++i) out += b.color;
    return out;
}

int main() {
    Box b;
    std::printf("%s\n", (b * 2).c_str()); // calls operator*
    std::printf("%s\n", b.color.c_str());
    return 0;
}
Output
redred
red

C# v11.0.100

v11.0.100
var b = new Box();
var m = b.GetType().GetMethod("Greet", new[] { typeof(string) })!;
Console.WriteLine(m.Invoke(b, new object[] { "hi" }));
Console.WriteLine(b.Color);

// C# has no magic methods: reflection calls members by name at runtime —
// the honest equivalent of __call
class Box {
    public string Color = "red";
    public string Greet(string who) => "called greet(" + who + ")";
}
Output
called greet(hi)
red

Go v1.27.4

v1.27.4
package main

import "fmt"

// Go has no magic methods: a map of functions plus an explicit Call is the
// hand-rolled equivalent
type Box struct {
	data map[string]func(args ...string) string
}

func NewBox() *Box {
	return &Box{data: map[string]func(args ...string) string{
		"greet": func(args ...string) string { return "called greet(" + args[0] + ")" },
	}}
}

func (b *Box) Call(name string, args ...string) string { // the explicit dispatch
	if f, ok := b.data[name]; ok {
		return f(args...)
	}
	return "no method " + name
}

func main() {
	b := NewBox()
	fmt.Println(b.Call("greet", "hi"))
	fmt.Println(b.Call("missing"))
}
Output
called greet(hi)
no method missing

Java v27.0.1

v27.0.1
import java.lang.reflect.Method;

public class Main {
    // Java has no magic methods: reflection is the runtime-dispatch route
    static class Box {
        public String greet(String who) { return "called greet(" + who + ")"; }
    }

    public static void main(String[] args) throws Exception {
        Box b = new Box();
        Method m = Box.class.getMethod("greet", String.class);
        System.out.println(m.invoke(b, "hi"));
    }
}
Output
called greet(hi)

JavaScript v26.13.1

v26.13.1
// JS has no per-class magic methods: the Proxy metaprogram wraps a callable
// target and intercepts get / set / apply traps
const target = () => {};
target.data = {}; // plain storage on the target, outside the traps
const box = new Proxy(target, {
  get(target, key) { // property read
    return key in target.data ? target.data[key] : "(missing)";
  },
  set(target, key, value) { // property write
    target.data[key] = value;
    return true;
  },
  apply(target, thisArg, args) { // proxy called as a function (callable target)
    return args[0] * 2;
  },
});

box.color = "red";         // set trap
console.log(box.color);    // get trap
console.log(box.missing);  // get trap fallback
console.log(box(21));      // apply trap
Output
red
(missing)
42

PHP v8.6.0

v8.6.0
class Box {
    private array $data = [];

    public function __get(string $name): mixed { // undeclared property read
        return $this->data[$name] ?? "(missing)";
    }
    public function __set(string $name, mixed $value): void { // undeclared property write
        $this->data[$name] = $value;
    }
    public function __call(string $name, array $args): string { // undeclared method call
        return "called " . $name . "(" . implode(",", $args) . ")";
    }
    public function __toString(): string { // object used as a string
        return "Box[" . count($this->data) . "]";
    }
    public function __invoke(int $n): int { // object called as a function
        return $n * 2;
    }
}

$b = new Box();
$b->color = "red";          // fires __set
echo $b->color, "\n";       // fires __get
echo $b->missing, "\n";     // __get again: the fallback path
echo $b->greet("hi"), "\n"; // fires __call
echo $b, "\n";              // fires __toString
echo $b(21), "\n";          // fires __invoke
Output
red
(missing)
called greet(hi)
Box[1]
42

Python v3.15.2

v3.15.2
class Box:
    def __init__(self):
        self._data = {}

    def __getattr__(self, name):  # fires on MISSING attribute reads
        return self._data.get(name, "(missing)")

    def __setattr__(self, name, value):  # fires on EVERY attribute write
        if name == "_data":              # bootstrap the storage itself
            super().__setattr__(name, value)
        else:
            self._data[name] = value

    def __call__(self, n):  # object called as a function
        return n * 2

    def __repr__(self):  # object rendered (print/repl)
        return f"Box[{len(self._data)}]"

b = Box()
b.color = "red"    # fires __setattr__
print(b.color)     # plain dict read
print(b.missing)   # fires __getattr__
print(b(21))       # fires __call__
print(b)           # fires __repr__
Output
red
(missing)
42
Box[1]

Rust v1.99.1

v1.99.1
// Rust has no runtime magic: interception is TRAIT-based and statically
// dispatched — Display for stringification is the classic example
use std::fmt;

struct Box2 {
    color: String,
}

impl fmt::Display for Box2 { // the Display trait plays __toString's role
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Box[{}]", self.color)
    }
}

fn main() {
    let b = Box2 { color: "red".to_string() };
    println!("{}", b);       // Display, resolved at compile time
    println!("{}", b.color); // a plain field read — no interception layer
}
Output
Box[red]
red

TypeScript v26.13.1

v26.13.1
// TS: like JS, Proxy is the interception tool; types annotate the traps
interface BoxData {
  [key: string]: string;
}

const box = new Proxy({ data: {} as BoxData }, {
  get(target, key): string {
    return key in target.data ? target.data[key as string] : "(missing)";
  },
  set(target, key, value): boolean {
    target.data[key as string] = String(value);
    return true;
  },
});

box.color = "red";        // set trap
console.log(box.color);   // get trap
console.log(box.missing); // get trap fallback
Output
red
(missing)

Language differences

C: no interception machinery at all — a function-pointer table (example) IS the dispatch; every bit of "magic" is wired explicitly.

C++: no runtime interception; operator overloading is the closest "magic" (example) — call sites look built-in but resolve statically at compile time; __toString maps to operator<<, and __get/__set/__call have no counterpart.

C#: no magic methods — reflection GetMethod/Invoke (example) dispatches by name at runtime; DynamicObject (DLR) additionally offers dynamic interception akin to __get/__call.

Go: no magic methods — a map of functions plus an explicit Call (example) is the hand-rolled dispatch; fmt implicitly recognizes convention interfaces like Stringer (String() is called on print), the closest thing to __toString's hidden hook.

Java: no magic methods — reflection (example) covers runtime by-name invocation; fixed-name conventions like toString() are recognized by println; no property/method-level interception.

JavaScript: no per-class magic methods — Proxy metaprogramming (example) intercepts get/set/apply traps per object; getter/setter accessors cover property interception.

PHP: the magic-method table (5 shown in the example): __get/__set intercept undeclared property reads/writes, __call intercepts undeclared method calls, __toString stringifies (implicitly implementing Stringable), __invoke lets the object be called as a function; the __ prefix is reserved and all must be public (constructor/destructor/clone excepted); __sleep/__wakeup are soft-deprecated in 8.5 — use __serialize/__unserialize.

Python: the full dunder family (example): __getattr__ fires only when the attribute is missing (same semantics as PHP __get), __setattr__ fires on every write, __call__/__repr__ map to __invoke/__toString; there is no direct counterpart to method-level __call (__getattr__ can improvise).

Rust: no runtime magic — interception lives at the trait layer and dispatches statically (example): Display/Deref/From are compile-resolved conventions; no by-name interception of properties or methods exists.

TypeScript: the same Proxy as JS (example) plus typed trap signatures; getter/setter syntax (same as JS accessors) covers property interception at compile time.