1

I am working through some old code for a tKinter GUI and at the top of their code they create the following definition:

def _(text):
    return text

The code then proceeds to use the _ function around almost all of the strings being passed to the tKinter widgets. For example:

editmenu.add_command(label=_("Paste"), command=parent.onPaste)

Is there a reason for using the function here as opposed to just passing the string?

I've removed the _ function from around a few of the strings and haven't run into any issues. Just curious if this has a real purpose.

Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
Dacoolinus
  • 388
  • 1
  • 10
  • 4
    No, except one would intend to alter all of these strings in a certain way. As written, it is just overhead. – Thingamabobs Nov 04 '22 at 15:54
  • I agree with @Thingamabobs - if this function were actually doing anything, then I'd say keep it. But as written it's just a waste...perhaps there was some initial intent behind this, but that's purely speculation at this point. – JRiggles Nov 04 '22 at 15:55
  • Related: https://stackoverflow.com/q/1962287/13629335 – Thingamabobs Nov 05 '22 at 06:35

1 Answers1

6

This is a stub for a pattern typically used for internationalization. The pattern is explicitly documented at https://docs.python.org/3/library/gettext.html#deferred-translations

_("Foo") is intended to have _ look up the string Foo in the current user's configured language.

Putting the stub in now -- before any translation tables have actually been built -- makes it easy to search for strings that need to be translated, and avoids folks needing to go through the software figuring out which strings are intended for system-internal vs user-visible uses later. (It also helps guide programmers to avoid making common mistakes like using the same string constants for both user-visible display and save file formats or wire communications).


Understanding this is important, because it guides how this should be used. Don't use _("Save %s".format(name)); instead, use _("Save %s").format(filename) so the folks who are eventually writing translation tables can adjust the format strings, and so those strings don't need to have user-provided content (which obviously can't be known ahead-of-time) within them.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    Related docs: https://docs.python.org/3/library/i18n.html and the particular habit at: https://docs.python.org/3/library/gettext.html#deferred-translations – Thingamabobs Nov 04 '22 at 16:00