Python locale.getlocale() Function



The Python locale.getlocale() function is used to retrieve the current locale setting for the program. It returns a tuple containing the language code and encoding for the active locale setting.

This function is useful for checking the locale currently set in the environment, which may have been modified using locale.setlocale().

Syntax

Following is the syntax of the Python locale.getlocale() function −

locale.getlocale(category=locale.LC_CTYPE)

Parameters

This function accepts the locale category to be retrieved as an optional parameter. The default is locale.LC_CTYPE.

Return Value

This function returns a tuple (language, encoding) where −

  • language: A string representing the language and country code (e.g., 'en_US').
  • encoding: A string representing the character encoding used by the locale (e.g., 'UTF-8').

Example 1

Following is an example of the Python locale.getlocale() function. Here, we retrieve the program's current locale setting −

import locale

default_locale = locale.getlocale()
print("Current Locale:", default_locale)

Following is the output of the above code (output may vary depending on the system) −

Current Locale: ('C', 'UTF-8')

Example 2

Here, we retrieve and display only the language code and encoding separately −

import locale

current_locale = locale.getlocale()
language, encoding = current_locale
print("Language Code:", language)
print("Encoding:", encoding)

Output of the above code is as follows (output may vary based on system settings) −

Language Code: C
Encoding: UTF-8

Example 3

Now, we set a new locale using the locale.setlocale() function and verify the change using locale.getlocale() −

import locale

locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
updated_locale = locale.getlocale()
print("Updated Locale:", updated_locale)

The result obtained is as shown below (output may vary) −

Updated Locale: ('fr_FR', 'UTF-8')

Example 4

We can use the locale.getlocale() function to check if the current locale is set to a specific language −

import locale

def is_locale_french():
   language, _ = locale.getlocale()
   return language == "fr_FR"

print("Is French Locale Set?:", is_locale_french())

The result produced is as follows (output may vary) −

Is French Locale Set?: False
python_modules.htm
Advertisements