0

I want to make different language files for my script, and the way I intended to set this up (after some googling) is that based on user's choice, a .py file (%cwd%\locale\en.py, %cwd%\locale\ru.py etc) with all strings saved as variables is imported using importlib.import_module, and all text after that is formatted with f-strings using variables from the imported file.

I've tried providing strings with the relative name such as locale.en (as I would in a normal import) and the full path acquired using str(Path(Path.cwd() / 'locale' / 'en.py')) (print showed that the directory is acquired correctly), and in both cases I get a ModuleNotFoundError.

I kinda sorta understand why I would get it using the relative name, but how come the full path is not enough? I keep finding answers mentioning that __init__.py is required in the locale folder, but I also find answers that make no mention of it.

Not sure if it's relevant, but in the full path's ModuleNotFoundError every backslash is doubled (e.g. C:\\Script\\locale\\en)

bqback
  • 55
  • 9
  • 3
    To do this properly, have you considered gettext? https://docs.python.org/3/library/gettext.html – deceze Feb 13 '21 at 19:16
  • 1
    it sounds like you're giving a path like '/path/to/module' to importlib.import_module? I believe it takes a dotted module path, like an import statement - importlib.import_module('relative.module.path'). An example of what you're actually doing in your code would be helpful. – zyd Feb 13 '21 at 19:18
  • 1
    Doing this by dynamic imports sounds doable but difficult. I agree with @deceze that `gettext` is the better option. If for some reason that doesn't work, putting the data into CSVs seems like a better option than hardcoding it in `.py` files. – Samwise Feb 13 '21 at 19:19
  • 1
    `gettext` has been around for years and is fully debugged. Don't reinvent the wheel… – martineau Feb 13 '21 at 19:20
  • @zyd I tried both (`importlib.import_module('locale.en')`, `importlib.import_module('path/locale/en.py')`) with both producing `ModuleNotFoundError`. – bqback Feb 13 '21 at 20:10
  • I didn't know about `gettext`, will try it out. Thanks to everyone who mentioned it. – bqback Feb 13 '21 at 20:11

0 Answers0