API Reference๏
This page contains the complete API documentation for the countryflag library.
Main Module๏
CountryFlag - A Python package for converting country names into emoji flags.
This package provides functionality to convert country names to emoji flags and vice versa, with support for various formats, fuzzy matching, and region/continent grouping.
Features: - Convert country names to emoji flags - Reverse lookup (flag to country name) - Region/continent grouping - Multiple output formats (text, JSON, CSV) - Fuzzy matching for country names - Interactive CLI mode with autocompletion - Asynchronous and parallel processing - Memory and disk caching for improved performance
Example
>>> import countryflag
>>> countryflag.getflag(['Germany', 'BE', 'United States', 'Japan'])
'๐ฉ๐ช ๐ง๐ช ๐บ๐ธ ๐ฏ๐ต'
- For more advanced usage, use the core classes directly:
>>> from countryflag.core import CountryFlag >>> cf = CountryFlag() >>> flags, pairs = cf.get_flag(['Germany', 'France', 'Italy']) >>> flags '๐ฉ๐ช ๐ซ๐ท ๐ฎ๐น'
For more information, see the documentation at: https://countryflag.readthedocs.io/
- countryflag.getflag(countries, separator=' ')[source]๏
Convert country names to emoji flags.
This is a convenience function that creates a CountryFlag instance and calls get_flag() on it. For backward compatibility, it returns just the string of flags by default, but can optionally return the full tuple with pairs.
- Parameters:
- Returns:
A string containing emoji flags separated by the specified separator.
- Return type:
- Raises:
TypeError โ If countries argument is not a string or list of strings.
InvalidCountryError โ If a country name cannot be converted to a flag.
Example
>>> getflag(['Germany', 'BE', 'United States of America', 'Japan']) '๐ฉ๐ช ๐ง๐ช ๐บ๐ธ ๐ฏ๐ต'
- countryflag.get_ascii_flag(country_name)[source]๏
Get ASCII art flag for a country, with fallback to Unicode emoji.
This is a convenience function that creates a CountryFlag instance and calls get_ascii_flag() on it. It attempts to load ASCII art from embedded resources, falling back to Unicode emoji flags when resources are missing.
- Parameters:
country_name (str) โ The country name or ISO code.
- Returns:
ASCII art flag if available, otherwise Unicode emoji flag.
- Return type:
- Raises:
TypeError โ If country_name is not a string.
InvalidCountryError โ If the country name cannot be converted.
Example
>>> result = get_ascii_flag("DE") >>> isinstance(result, str) True
- class countryflag.CountryFlag(language='en', cache=None)[source]๏
Bases:
objectClass to handle country flag operations.
This class provides methods for converting country names to emoji flags, reverse lookup (flag to country name), and region-based operations.
- _converter๏
The CountryConverterSingleton instance.
- _language๏
The language code for output.
- _cache๏
The cache instance to use (optional).
Example
>>> cf = CountryFlag() >>> flags, _ = cf.get_flag(["United States", "Canada", "Mexico"]) >>> flags '๐บ๐ธ ๐จ๐ฆ ๐ฒ๐ฝ'
Initialize the CountryFlag class.
- Parameters:
- classmethod clear_global_cache()[source]๏
Clear the global cache. Useful for testing or resetting cache state.
This method clears the shared cache instance used by all CountryFlag instances that donโt have a custom cache provided.
Example
>>> CountryFlag.clear_global_cache()
- Return type:
None
- set_language(language)[source]๏
Set the language for country names.
- Parameters:
language (str) โ The ISO 639-1 language code.
- Return type:
None
- validate_country_name(country_name)[source]๏
Validate if a country name can be converted to an ISO2 code.
- Parameters:
country_name (str) โ The country name to validate.
- Returns:
True if the country name is valid, False otherwise.
- Return type:
Example
>>> cf = CountryFlag() >>> cf.validate_country_name("United States") True >>> cf.validate_country_name("Not a Country") False
- get_supported_countries()[source]๏
Get a list of supported country names and their ISO2 codes.
Example
>>> cf = CountryFlag() >>> countries = cf.get_supported_countries() >>> len(countries) > 0 True
- get_flags_by_region(region, separator=' ')[source]๏
Get flags for all countries in a specific region/continent.
- Parameters:
- Returns:
- A tuple containing the flags string and
a list of (country_name, flag) pairs.
- Return type:
- Raises:
RegionError โ If the region is not supported.
Example
>>> cf = CountryFlag() >>> flags, pairs = cf.get_flags_by_region("Europe") >>> len(pairs) > 0 True
- get_flag(country_names, separator=' ', fuzzy_matching=False, fuzzy_threshold=0.6)[source]๏
Convert country names to emoji flags.
- Parameters:
country_names (List[str]) โ A list of country names to convert to flags.
separator (str) โ The separator to use between flags (default: space).
fuzzy_matching (bool) โ Whether to use fuzzy matching for country names.
fuzzy_threshold (float) โ The similarity threshold for fuzzy matching (0-1).
- Returns:
- A tuple containing the flags string and
a list of (country_name, flag) pairs.
- Return type:
- Raises:
InvalidCountryError โ If a country name cannot be converted to a flag.
Example
>>> cf = CountryFlag() >>> flags, pairs = cf.get_flag(["United States", "Canada"]) >>> flags '๐บ๐ธ ๐จ๐ฆ' >>> pairs [('United States', '๐บ๐ธ'), ('Canada', '๐จ๐ฆ')]
- reverse_lookup(emoji_flags)[source]๏
Convert emoji flags to country names with robust handling of edge cases.
This method provides enhanced reverse lookup that handles: - Standard regional indicator flags (๐บ๐ธ โ United States) - Alternative ISO codes (๐ฌ๐ง and ๐บ๐ฐ โ United Kingdom) - Special territories (๐ฆ๐จ โ Ascension Island) - Regional indicator normalization
- Parameters:
emoji_flags (List[str]) โ A list of emoji flags to convert to country names.
- Returns:
A list of tuples containing (flag, country_name).
- Return type:
- Raises:
ReverseConversionError โ If a flag emoji cannot be converted to a country name.
Example
>>> cf = CountryFlag() >>> pairs = cf.reverse_lookup(["๐บ๐ธ", "๐ฌ๐ง", "๐บ๐ฐ"]) >>> pairs [('๐บ๐ธ', 'United States'), ('๐ฌ๐ง', 'United Kingdom')]
- format_output(country_flag_pairs, output_format='text', separator=' ')[source]๏
Format the output according to the specified format.
- Parameters:
- Returns:
The formatted output.
- Return type:
Example
>>> cf = CountryFlag() >>> flags, pairs = cf.get_flag(["United States", "Canada"]) >>> cf.format_output(pairs, "json") '[{"country": "US", "flag": "๐บ๐ธ"}]'
- get_ascii_flag(country_name)[source]๏
Get ASCII art flag for a country, with fallback to Unicode emoji.
This method attempts to load ASCII art from embedded resources. If the resource is missing or cannot be loaded, it falls back to returning the Unicode emoji flag instead of raising an error.
- Parameters:
country_name (str) โ The country name or ISO code.
- Returns:
ASCII art flag if available, otherwise Unicode emoji flag.
- Return type:
Example
>>> cf = CountryFlag() >>> result = cf.get_ascii_flag("DE") >>> isinstance(result, str) True
- exception countryflag.CountryFlagError(message)[source]๏
Bases:
ExceptionBase exception for countryflag errors.
This is the base class for all exceptions raised by the countryflag package.
- message๏
The error message.
Initialize the exception.
- Parameters:
message (str) โ The error message.
- Return type:
None
- __init__(message)[source]๏
Initialize the exception.
- Parameters:
message (str) โ The error message.
- Return type:
None
- message๏
- exception countryflag.InvalidCountryError(message, country)[source]๏
Bases:
CountryFlagErrorException raised when an invalid country name is provided.
This exception is raised when a country name cannot be converted to an ISO2 code.
- message๏
The error message.
- country๏
The invalid country name.
Initialize the exception.
- Parameters:
- Return type:
None
- country๏
- exception countryflag.ReverseConversionError(message, flag)[source]๏
Bases:
CountryFlagErrorException raised when a flag emoji cannot be converted to a country name.
This exception is raised when a flag emoji cannot be mapped to a country name.
- message๏
The error message.
- flag๏
The flag emoji that could not be converted.
Initialize the exception.
- Parameters:
- Return type:
None
- flag๏
- exception countryflag.RegionError(message, region)[source]๏
Bases:
CountryFlagErrorException raised when an invalid region is provided.
This exception is raised when a region name is not recognized.
- message๏
The error message.
- region๏
The invalid region name.
Initialize the exception.
- Parameters:
- Return type:
None
- region๏
- exception countryflag.CacheError(message, key=None)[source]๏
Bases:
CountryFlagErrorException raised when there is an error with the cache.
This exception is raised when there is an error reading from or writing to the cache.
- message๏
The error message.
- key๏
The cache key that caused the error (optional).
Initialize the exception.
- Parameters:
- Return type:
None
- key๏
- exception countryflag.PluginError(message, plugin_name=None)[source]๏
Bases:
CountryFlagErrorException raised when there is an error with a plugin.
This exception is raised when there is an error loading or using a plugin.
- message๏
The error message.
- plugin_name๏
The name of the plugin that caused the error (optional).
Initialize the exception.
- Parameters:
- Return type:
None
- plugin_name๏
Core API๏
Country flag functionality for the countryflag package.
This module contains the CountryFlag class that provides methods for converting country names to emoji flags and vice versa.
- class countryflag.core.flag.CountryFlag(language='en', cache=None)[source]๏
Bases:
objectClass to handle country flag operations.
This class provides methods for converting country names to emoji flags, reverse lookup (flag to country name), and region-based operations.
- _converter๏
The CountryConverterSingleton instance.
- _language๏
The language code for output.
- _cache๏
The cache instance to use (optional).
Example
>>> cf = CountryFlag() >>> flags, _ = cf.get_flag(["United States", "Canada", "Mexico"]) >>> flags '๐บ๐ธ ๐จ๐ฆ ๐ฒ๐ฝ'
Initialize the CountryFlag class.
- Parameters:
- classmethod clear_global_cache()[source]๏
Clear the global cache. Useful for testing or resetting cache state.
This method clears the shared cache instance used by all CountryFlag instances that donโt have a custom cache provided.
Example
>>> CountryFlag.clear_global_cache()
- Return type:
None
- set_language(language)[source]๏
Set the language for country names.
- Parameters:
language (str) โ The ISO 639-1 language code.
- Return type:
None
- validate_country_name(country_name)[source]๏
Validate if a country name can be converted to an ISO2 code.
- Parameters:
country_name (str) โ The country name to validate.
- Returns:
True if the country name is valid, False otherwise.
- Return type:
Example
>>> cf = CountryFlag() >>> cf.validate_country_name("United States") True >>> cf.validate_country_name("Not a Country") False
- get_supported_countries()[source]๏
Get a list of supported country names and their ISO2 codes.
Example
>>> cf = CountryFlag() >>> countries = cf.get_supported_countries() >>> len(countries) > 0 True
- get_flags_by_region(region, separator=' ')[source]๏
Get flags for all countries in a specific region/continent.
- Parameters:
- Returns:
- A tuple containing the flags string and
a list of (country_name, flag) pairs.
- Return type:
- Raises:
RegionError โ If the region is not supported.
Example
>>> cf = CountryFlag() >>> flags, pairs = cf.get_flags_by_region("Europe") >>> len(pairs) > 0 True
- get_flag(country_names, separator=' ', fuzzy_matching=False, fuzzy_threshold=0.6)[source]๏
Convert country names to emoji flags.
- Parameters:
country_names (List[str]) โ A list of country names to convert to flags.
separator (str) โ The separator to use between flags (default: space).
fuzzy_matching (bool) โ Whether to use fuzzy matching for country names.
fuzzy_threshold (float) โ The similarity threshold for fuzzy matching (0-1).
- Returns:
- A tuple containing the flags string and
a list of (country_name, flag) pairs.
- Return type:
- Raises:
InvalidCountryError โ If a country name cannot be converted to a flag.
Example
>>> cf = CountryFlag() >>> flags, pairs = cf.get_flag(["United States", "Canada"]) >>> flags '๐บ๐ธ ๐จ๐ฆ' >>> pairs [('United States', '๐บ๐ธ'), ('Canada', '๐จ๐ฆ')]
- reverse_lookup(emoji_flags)[source]๏
Convert emoji flags to country names with robust handling of edge cases.
This method provides enhanced reverse lookup that handles: - Standard regional indicator flags (๐บ๐ธ โ United States) - Alternative ISO codes (๐ฌ๐ง and ๐บ๐ฐ โ United Kingdom) - Special territories (๐ฆ๐จ โ Ascension Island) - Regional indicator normalization
- Parameters:
emoji_flags (List[str]) โ A list of emoji flags to convert to country names.
- Returns:
A list of tuples containing (flag, country_name).
- Return type:
- Raises:
ReverseConversionError โ If a flag emoji cannot be converted to a country name.
Example
>>> cf = CountryFlag() >>> pairs = cf.reverse_lookup(["๐บ๐ธ", "๐ฌ๐ง", "๐บ๐ฐ"]) >>> pairs [('๐บ๐ธ', 'United States'), ('๐ฌ๐ง', 'United Kingdom')]
- format_output(country_flag_pairs, output_format='text', separator=' ')[source]๏
Format the output according to the specified format.
- Parameters:
- Returns:
The formatted output.
- Return type:
Example
>>> cf = CountryFlag() >>> flags, pairs = cf.get_flag(["United States", "Canada"]) >>> cf.format_output(pairs, "json") '[{"country": "US", "flag": "๐บ๐ธ"}]'
- get_ascii_flag(country_name)[source]๏
Get ASCII art flag for a country, with fallback to Unicode emoji.
This method attempts to load ASCII art from embedded resources. If the resource is missing or cannot be loaded, it falls back to returning the Unicode emoji flag instead of raising an error.
- Parameters:
country_name (str) โ The country name or ISO code.
- Returns:
ASCII art flag if available, otherwise Unicode emoji flag.
- Return type:
Example
>>> cf = CountryFlag() >>> result = cf.get_ascii_flag("DE") >>> isinstance(result, str) True
Data Models๏
Data models for the countryflag package.
This module contains data classes and models used throughout the countryflag package.
Custom Exceptions๏
Exceptions for the countryflag package.
This module contains custom exceptions raised by the countryflag package.
- exception countryflag.core.exceptions.CountryFlagError(message)[source]๏
Bases:
ExceptionBase exception for countryflag errors.
This is the base class for all exceptions raised by the countryflag package.
- message๏
The error message.
Initialize the exception.
- Parameters:
message (str) โ The error message.
- Return type:
None
- __init__(message)[source]๏
Initialize the exception.
- Parameters:
message (str) โ The error message.
- Return type:
None
- message๏
- exception countryflag.core.exceptions.InvalidCountryError(message, country)[source]๏
Bases:
CountryFlagErrorException raised when an invalid country name is provided.
This exception is raised when a country name cannot be converted to an ISO2 code.
- message๏
The error message.
- country๏
The invalid country name.
Initialize the exception.
- Parameters:
- Return type:
None
- country๏
- exception countryflag.core.exceptions.ReverseConversionError(message, flag)[source]๏
Bases:
CountryFlagErrorException raised when a flag emoji cannot be converted to a country name.
This exception is raised when a flag emoji cannot be mapped to a country name.
- message๏
The error message.
- flag๏
The flag emoji that could not be converted.
Initialize the exception.
- Parameters:
- Return type:
None
- flag๏
- exception countryflag.core.exceptions.RegionError(message, region)[source]๏
Bases:
CountryFlagErrorException raised when an invalid region is provided.
This exception is raised when a region name is not recognized.
- message๏
The error message.
- region๏
The invalid region name.
Initialize the exception.
- Parameters:
- Return type:
None
- region๏
- exception countryflag.core.exceptions.CacheError(message, key=None)[source]๏
Bases:
CountryFlagErrorException raised when there is an error with the cache.
This exception is raised when there is an error reading from or writing to the cache.
- message๏
The error message.
- key๏
The cache key that caused the error (optional).
Initialize the exception.
- Parameters:
- Return type:
None
- key๏
- exception countryflag.core.exceptions.PluginError(message, plugin_name=None)[source]๏
Bases:
CountryFlagErrorException raised when there is an error with a plugin.
This exception is raised when there is an error loading or using a plugin.
- message๏
The error message.
- plugin_name๏
The name of the plugin that caused the error (optional).
Initialize the exception.
- Parameters:
- Return type:
None
- plugin_name๏
Utilities๏
- countryflag.utils.text.norm_newlines(s)[source]๏
Normalize newlines in a string to Unix format and strip trailing whitespace.
Converts Windows-style CRLF (rn) line endings to Unix-style LF (n) and removes trailing whitespace from the string.
Validation utility functions for the countryflag package.
This module contains utility functions for validating inputs and outputs.
- countryflag.utils.validation.require(predicate, message='Precondition failed')[source]๏
Decorator to enforce preconditions using design by contract.
- Parameters:
- Returns:
The decorated function.
- Raises:
ValueError โ If the precondition is not satisfied.
Example
>>> @require(lambda x: x > 0, "x must be positive") ... def sqrt(x): ... return x ** 0.5 >>> sqrt(4) 2.0 >>> sqrt(-1) Traceback (most recent call last): ... ValueError: x must be positive in sqrt
- countryflag.utils.validation.ensure(predicate, message='Postcondition failed')[source]๏
Decorator to enforce postconditions using design by contract.
- Parameters:
- Returns:
The decorated function with postcondition checking.
- Raises:
ValueError โ If the postcondition is not satisfied.
Example
>>> @ensure(lambda result: result >= 0, "result must be non-negative") ... def abs(x): ... return -x # Bug: should be abs(x) >>> abs(1) Traceback (most recent call last): ... ValueError: result must be non-negative in abs
- countryflag.utils.validation.runtime_typechecked(func)[source]๏
Decorator to add runtime type checking to a function.
- Parameters:
func (Callable[[...], T]) โ The function to decorate.
- Returns:
The decorated function with runtime type checking.
- Raises:
TypeError โ If the arguments or return value do not match the type annotations.
- Return type:
Callable[[โฆ], T]
Example
>>> @runtime_typechecked ... def add(x: int, y: int) -> int: ... return x + y >>> add(1, 2) 3 >>> add("1", 2) Traceback (most recent call last): ... TypeError: ...