Skip to content

prefer-env-translation (ODW8161)

Preview (since 0.16.2.2) · Related issues · View source

Derived from the odoo linter.

Fix is sometimes available.

This rule is unstable and in preview. The --preview flag is required for use.

What it does

Checks for calls to the bare _()/_lt() translation functions.

Why is this bad?

Since Odoo 18.0, self.env._() is preferred over the bare _()/_lt() functions.

The rule only applies from Odoo 18.0 on: self.env._ does not exist in earlier versions, so on an older codebase the bare _() is the only correct call. Configure the targeted version with the odoo-version setting; without it the rule stays enabled.

Inside an http.Controller the rule instead applies from Odoo 19.0 on, the version that gave Controller its env property. On 18.0 a controller reaches the environment through request.env alone, so there is no self.env._ to recommend and the call is not reported at all — reporting it would name a replacement that does not exist on that version.

Example

def my_method(self):
    return _("Hello")

Use instead:

def my_method(self):
    return self.env._("Hello")

Fix safety

The rewrite is only offered where self.env exists: inside a method of an Odoo model or of an http.Controller. At module level, in a plain function, in a @staticmethod, in a nested function or in a class that is not Odoo's, the call is reported without a fix, since self.env would resolve to nothing there.

The same goes for what the call resolves to: only odoo._/odoo._lt are rewritten, which covers an aliased import (from odoo import _ as lt) and leaves a _ that came from gettext, or a local of that name, reported but untouched.