How to use gettext with python >3.6 f-strings

前端 未结 2 1510
忘了有多久
忘了有多久 2020-12-17 07:43

Previously you would use gettext as following:

_(\'Hey {},\').format(username)

but what about new Python\'s f-string?

相关标签:
2条回答
  • 2020-12-17 08:25

    'Hey {},' is contained in your translation dictionary as is.

    If you use f'Hey {username},', that creates another string, which won't be translated.

    In that case, the format method remains the only one useable.

    0 讨论(0)
  • 2020-12-17 08:46

    Preface

    I know this question is quite old and already has a very legitimate answer but I’m going to be bold and give my answer to this as I landed here while searching, and I am a fan of using f-strings myself and don’t want to lose out on its use but also support I18N. (i.e: I want my cake and eat it too)

    Answer

    My solution is to make a function f() which performs the f-string interpolation after gettext has been called.

    from inspect import currentframe
    
    def f(s):
        frame = currentframe().f_back
        return eval(f"f'{s}'", frame.f_locals, frame.f_globals)
    

    Now you just wrap _(...) in f() and don’t preface the string with an f:

    f(_('Hey, {username}'))
    

    Note of caution

    I’m usually against the use of eval as it could make the function potentially unsafe, but I personally think it should be justified here, so long as you’re aware of what’s being formatted. That said use at your own risk.

    Remember

    This isn’t a perfect solution, this is just my solution. As per PEP 498 states each formatting method “have their advantages, but in addition have disadvantages” including this.

    For example if you need to change the expression inside the string then it will no longer match, therefore not be translated unless you also update your .po file as well. Also if you’re not the one translating them and you use an expression that’s hard to decipher what the outcome will be then that can cause miscommunication or other issues in translation.

    0 讨论(0)
提交回复
热议问题