Import by file/module name in GAE
Question: I am trying to make a simple localization module that takes a key name and
returns the localized string based on the language given. The language is one
of the constants and maps to a python file that contains the string table. I
want to do this dynamically at runtime. Below is my approach, but GAE does not
support the imp module. Is there an alternative way to do this?

    
    
    import logging
    import imp
    
    import localizable
    
    LANGUAGE_EN = "en"
    LANGUAGE_JP = "ja"
    
    class Localizer(object):
        """
        Returns a localized string corresponding to unique keys
        """
        @classmethod
        def localize(cls, language = LANGUAGE_EN, key = None):
            user_language = imp.load_source("localizable.%s" % language, "/")
            if (user_language):
                return user_language.Locale.localize(key)
            else:
                logging.error("Localizable file was not found")
                return ""
    

I put the language files in localizable/en.py, etc.


Answer: The alternative to the imp module that (I believe) should be available in GAE
is `__import__()`. It's in fact what the 'import' statement calls to do the
actual importing.

    
    
    user_language = getattr(__import__('localizable.%s' % language), language)
    

or

    
    
    user_language __import__('localizable.%s' % language, {}, globals(), [''])
    

(passing a non-empty fourth argument to `__import__` causes it to return the
right-most module in the first argument, instead of the left-most. It's a
little hacky, so people tend to prefer the first solution over the second.)

