Translation anti-patterns

Translating a variable

Bad :-1: :

def say(text):
    print(_(text))  # <- not extracted but maybe translated here

say("Hello")

Good :+1: :

def say(text):
    print(text)

say(_("Hello"))  # <- extracted and translated here

We extract translatable strings from the source code. They can only be extracted if the original strings themselves are wrapped in the translation function.

The only exception where translating a variable is okay is when we can rely on the text being extracted in another way, e.g. doctype names and field labels.

Example: fix: translate display text passed to validate_account_head by barredterra · Pull Request #43057 · frappe/erpnext · GitHub

Constructing sentences

Bad :-1: :

message = _("Created a {0} Invoice!").format(_(invoice_type))

Good :+1: :

if invoice_type == "Sales":
    message = _("Created a Sales Invoice!")
elif invoice_type == "Purchase":
    message = _("Created a Purchase Invoice!")

It’s easiest to translated whole sentences. Translating parts of a constructed sentence correctly is close to impossible.

Examples:

Translated document names

Bad :-1: :

cg = frappe.new_doc("Customer Group")
cg.name = _("Non Profit")
cg.insert()

# ...

cg = frappe.get_doc("Customer Group",  _("Non Profit"))
# or, equally bad, in this case:
cg = frappe.get_doc("Customer Group",  "Non Profit")

Good :+1: :

cg = frappe.new_doc("Customer Group")
cg.name = "Non Profit"
cg.insert()

# ...

cg = frappe.get_doc("Customer Group",  "Non Profit")

Translations can change after insertion. The current user can have a different language than the one who created the record. Document names should be translated only for display, never in the database.

Examples:

12 Likes

Translated Document Name

So ErpNext is doing this anti-pattern when creating chart of accounts?

Yes, but only the creation part, not the fetching part. The consequence is that we can never hardcode the account name/id. We fetch it in a different way, for example by account type.

Hi @rmeyer

Could this be test in github CI and pre-commit ?
It will increase the quality of contribution and force PR author to make it correctly.

I think there are too many exceptions to these guidelines. And most of the real occurrences aren’t as simple to spot as in the examples above.