Return Value from init

ID

python.no_constructor_return

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

reliability, suspicious-construct

Description

Reports init methods that contain return <expr> where <expr> is not None. Python’s data model requires init to return None; returning any other value raises TypeError when the class is instantiated. The most common cause is confusion with new (which does return the constructed instance) or a factory function that should have been a @classmethod.

class Bad:
    def __init__(self, x):
        self.x = x
        return self            # FLAW

class Good:
    def __init__(self, x):
        self.x = x
        return                 # OK — bare return

class GoodFactory:
    @classmethod
    def from_dict(cls, d):
        instance = cls(d["x"])
        return instance        # OK — classmethod, not __init__

Rationale

The error from a returning init only fires on instantiation, not on import. Static detection means the bug is fixed before the line ever runs.

Remediation

Drop the value from the return statement, or move the logic to new (uncommon) or to a classmethod factory that constructs and returns the instance.