I have implemented Fluent in my Python/Kivy app. I thought it worked fine, but now it seems to ignore when I change locales. Here is the (global) initialization in my Python app:
from fluent.runtime import FluentLocalization, FluentResourceLoader
loader = FluentResourceLoader(“languages/{locale}”)
language = FluentLocalization([“en”, “es”, “da”], [“main.ftl”], loader)
Later the user can change the selection, for instance like this:
language.locales = [‘da’,‘en’,‘es’]
AFTER that change, I instantiate a class that uses this in init:
This depends on the kind of app you are writing. Given that you are using Kivy, a single global for this might be fine, in which case you can use the global keyword:
from fluent.runtime import FluentLocalization, FluentResourceLoader
localization = None
def change_language(languages):
global localization
loader = FluentResourceLoader(“languages/{locale}”)
localization = FluentLocalization(languages, [“main.ftl”], loader)
# Ensure `localization` is always initialized
change_language([“en”, “es”, “da”])
# Also call `change_language` from other places
In other app architectures this could be a bad way to do it, and even with Kivy you may need to worry about other threads or modules that are importing this module and could end up with stale values. It might be better to ask on Kivy forums about what the best pattern for global mutable data is.
The code snippet I showed is getting a translation class to be used in a local context, with caching of these instances, on top of the caching that happens inside the translation class.
If you’re looking for a way still to make your global work, you’ll need to replace the localization class with one that does what you need. It’s not like you’re loosing a lot, because most of the actual logic in the implementation needs to be done differently for the architecture you’d be looking at.
The built-in localization class is really an opinionated way of implementing the concept, and alternative ways should substitute the one we’re shipping.
Thanks for the suggestions.
I think I will stick to something more simple for now, like this:
from fluent.runtime import FluentLocalization, FluentResourceLoader
language = None
‘#’ Only call this ONCE:
def set_language(languages):
global language
loader = FluentResourceLoader(‘languages/{locale}’)
language = FluentLocalization(languages, [‘main.ftl’], loader)