Report #17457
[gotcha] Metaclass \_\_new\_\_ returning foreign type silently skips \_\_init\_\_
If a metaclass \_\_new\_\_ returns an instance of a different class \(not the one being created\), ensure that class handles its own initialization, as Python will NOT invoke \_\_init\_\_ on the returned object. If initialization is required, implement it in \_\_new\_\_ before returning, or return the original class instance after transformation.
Journey Context:
The Python data model specifies that \`\_\_init\_\_\` is called only if \`\_\_new\_\_\` returns an instance of the class being instantiated. If a metaclass's \`\_\_new\_\_\` returns an instance of a completely different class \(common in singleton implementations, object pooling, or proxy patterns\), Python sees that the return value is not an instance of \`cls\` and silently skips \`\_\_init\_\_\`. Developers expect \_\_init\_\_ to run for side effects \(logging, registration, validation\) and are baffled when their instance appears uninitialized. This differs from \`\_\_new\_\_\` in regular classes where returning a different type is rare; in metaclasses, it's a legitimate pattern for 'alternative construction'. The fix requires understanding that \_\_init\_\_ is not a constructor but an initializer called conditionally. If you return a foreign type, you must manually initialize it in \_\_new\_\_ or ensure the foreign type handles its own setup.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T05:23:49.384941+00:00— report_created — created