Pythonic locale

Albert-Jan Roskam fomcl at yahoo.com
Mon Mar 2 06:42:49 EST 2015


Hi,

The Python locale standard libraries has some oddities and (long-standing) bugs.
Example oddity: SETlocale *returns* a locale; getlocale output cannot always be consumed by setlocale. Example bug: resetlocale fails in Windows. What is your opinion about the work-around code below? 


import sys
import os
import locale as locale_

locale_.setlocale(locale_.LC_ALL, "")
    
class PythonicLocale(object):
     
    LC_ALL = locale_.LC_ALL 
    LC_CTYPE = locale_.LC_CTYPE
    
    def __init__(self, failsafe=False):
        self.failsafe = failsafe
    
    @property
    def locale(self):
        """Partial wrapper for locale in standard library"""
        # LANG and LC_ALL sometimes not set
        if not sys.platform.startswith("win"):
            if locale_.getlocale()[0] is None and self.failsafe:
                os.environ["LANG"] = "en_US"
                os.environ["LC_ALL"] = "en_US.UTF-8"
        # getlocale output cannot be consumed by setlocale
        return locale_.setlocale(locale_.LC_ALL)

    @locale.setter
    def locale(self, category_and_locale_tuple):
        locale_.setlocale(*category_and_locale_tuple)

    @locale.deleter
    def locale(self):
        if sys.platform.startswith("win"):
            # resetlocale() is broken in Windows
            locale_.setlocale(locale_.LC_ALL, "")
        else: 
            locale_.resetlocale()

    def getdefaultlocale(self):
        return locale_.getdefaultlocale()


if __name__ == "__main__":
    locale = PythonicLocale() 
    # getter
    print locale.locale
    # setter
    locale.locale = (locale.LC_ALL, "german")
    print locale.locale
    # deleter
    del locale.locale
    # check if deleter worked
    print locale.locale

Thanks!

Regards,

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



More information about the Python-list mailing list