Home > Enterprise >  Why would someone pass a string through an empty function instead of using the string directly in Py
Why would someone pass a string through an empty function instead of using the string directly in Py

Time:11-05

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.

CodePudding user response:

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.

  • Related