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:
  • countries (str | List[str]) โ€“ A single country name or list of country names to convert to flags.

  • separator (str) โ€“ The separator to use between flags (default: space).

Returns:

A string containing emoji flags separated by the specified separator.

Return type:

str

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:

str

Raises:

Example

>>> result = get_ascii_flag("DE")
>>> isinstance(result, str)
True
class countryflag.CountryFlag(language='en', cache=None)[source]๏ƒ

Bases: object

Class 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:
  • language (str) โ€“ The language code for output (default: โ€˜enโ€™).

  • cache (Cache | None) โ€“ The cache instance to use (optional). If None, uses the shared global cache.

__init__(language='en', cache=None)[source]๏ƒ

Initialize the CountryFlag class.

Parameters:
  • language (str) โ€“ The language code for output (default: โ€˜enโ€™).

  • cache (Cache | None) โ€“ The cache instance to use (optional). If None, uses the shared global cache.

Return type:

None

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:

bool

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.

Returns:

A list of dictionaries containing country information.

Return type:

List[Dict[str, str]]

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:
  • region (Literal['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']) โ€“ The region/continent name (e.g., โ€œEuropeโ€, โ€œAsiaโ€).

  • separator (str) โ€“ The separator to use between flags (default: space).

Returns:

A tuple containing the flags string and

a list of (country_name, flag) pairs.

Return type:

Tuple[str, List[Tuple[str, str]]]

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:

Tuple[str, List[Tuple[str, str]]]

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:

List[Tuple[str, str]]

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:
  • country_flag_pairs (List[Tuple[str, str]]) โ€“ A list of (country, flag) pairs.

  • output_format (Literal['text', 'json', 'csv']) โ€“ The output format (text, json, csv).

  • separator (str) โ€“ The separator used between flags in text format.

Returns:

The formatted output.

Return type:

str

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:

str

Example

>>> cf = CountryFlag()
>>> result = cf.get_ascii_flag("DE")
>>> isinstance(result, str)
True
exception countryflag.CountryFlagError(message)[source]๏ƒ

Bases: Exception

Base 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: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • country (str) โ€“ The invalid country name.

Return type:

None

__init__(message, country)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • country (str) โ€“ The invalid country name.

Return type:

None

country๏ƒ
exception countryflag.ReverseConversionError(message, flag)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • flag (str) โ€“ The flag emoji that could not be converted.

Return type:

None

__init__(message, flag)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • flag (str) โ€“ The flag emoji that could not be converted.

Return type:

None

flag๏ƒ
exception countryflag.RegionError(message, region)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • region (str) โ€“ The invalid region name.

Return type:

None

__init__(message, region)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • region (str) โ€“ The invalid region name.

Return type:

None

region๏ƒ
exception countryflag.CacheError(message, key=None)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • key (str | None) โ€“ The cache key that caused the error (optional).

Return type:

None

__init__(message, key=None)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • key (str | None) โ€“ The cache key that caused the error (optional).

Return type:

None

key๏ƒ
exception countryflag.PluginError(message, plugin_name=None)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • plugin_name (str | None) โ€“ The name of the plugin that caused the error (optional).

Return type:

None

__init__(message, plugin_name=None)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • plugin_name (str | None) โ€“ The name of the plugin that caused the error (optional).

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: object

Class 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:
  • language (str) โ€“ The language code for output (default: โ€˜enโ€™).

  • cache (Cache | None) โ€“ The cache instance to use (optional). If None, uses the shared global cache.

__init__(language='en', cache=None)[source]๏ƒ

Initialize the CountryFlag class.

Parameters:
  • language (str) โ€“ The language code for output (default: โ€˜enโ€™).

  • cache (Cache | None) โ€“ The cache instance to use (optional). If None, uses the shared global cache.

Return type:

None

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:

bool

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.

Returns:

A list of dictionaries containing country information.

Return type:

List[Dict[str, str]]

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:
  • region (Literal['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']) โ€“ The region/continent name (e.g., โ€œEuropeโ€, โ€œAsiaโ€).

  • separator (str) โ€“ The separator to use between flags (default: space).

Returns:

A tuple containing the flags string and

a list of (country_name, flag) pairs.

Return type:

Tuple[str, List[Tuple[str, str]]]

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:

Tuple[str, List[Tuple[str, str]]]

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:

List[Tuple[str, str]]

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:
  • country_flag_pairs (List[Tuple[str, str]]) โ€“ A list of (country, flag) pairs.

  • output_format (Literal['text', 'json', 'csv']) โ€“ The output format (text, json, csv).

  • separator (str) โ€“ The separator used between flags in text format.

Returns:

The formatted output.

Return type:

str

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:

str

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.

class countryflag.core.models.CountryInfo(name, iso2, iso3, official_name, region='', subregion='', flag='')[source]๏ƒ

Bases: object

Data class representing country information.

Parameters:
name๏ƒ

The short name of the country.

Type:

str

iso2๏ƒ

The ISO 3166-1 alpha-2 code for the country.

Type:

str

iso3๏ƒ

The ISO 3166-1 alpha-3 code for the country.

Type:

str

official_name๏ƒ

The official name of the country.

Type:

str

region๏ƒ

The region/continent the country belongs to.

Type:

str

subregion๏ƒ

The subregion within the continent.

Type:

str

flag๏ƒ

The emoji flag for the country.

Type:

str

name: str๏ƒ
iso2: str๏ƒ
iso3: str๏ƒ
official_name: str๏ƒ
region: str = ''๏ƒ
subregion: str = ''๏ƒ
flag: str = ''๏ƒ
__post_init__()[source]๏ƒ

Generate the flag emoji if not provided.

Return type:

None

class countryflag.core.models.RegionDefinitions[source]๏ƒ

Bases: object

Class containing definitions of regions/continents.

This class provides standard region names and groupings.

REGIONS: ClassVar[List[str]] = ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']๏ƒ

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: Exception

Base 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: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • country (str) โ€“ The invalid country name.

Return type:

None

__init__(message, country)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • country (str) โ€“ The invalid country name.

Return type:

None

country๏ƒ
exception countryflag.core.exceptions.ReverseConversionError(message, flag)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • flag (str) โ€“ The flag emoji that could not be converted.

Return type:

None

__init__(message, flag)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • flag (str) โ€“ The flag emoji that could not be converted.

Return type:

None

flag๏ƒ
exception countryflag.core.exceptions.RegionError(message, region)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • region (str) โ€“ The invalid region name.

Return type:

None

__init__(message, region)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • region (str) โ€“ The invalid region name.

Return type:

None

region๏ƒ
exception countryflag.core.exceptions.CacheError(message, key=None)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • key (str | None) โ€“ The cache key that caused the error (optional).

Return type:

None

__init__(message, key=None)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • key (str | None) โ€“ The cache key that caused the error (optional).

Return type:

None

key๏ƒ
exception countryflag.core.exceptions.PluginError(message, plugin_name=None)[source]๏ƒ

Bases: CountryFlagError

Exception 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:
  • message (str) โ€“ The error message.

  • plugin_name (str | None) โ€“ The name of the plugin that caused the error (optional).

Return type:

None

__init__(message, plugin_name=None)[source]๏ƒ

Initialize the exception.

Parameters:
  • message (str) โ€“ The error message.

  • plugin_name (str | None) โ€“ The name of the plugin that caused the error (optional).

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.

Parameters:

s (str) โ€“ The input string to normalize

Returns:

The normalized string with Unix-style line endings and no trailing whitespace

Return type:

str

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:
  • predicate (Callable[[...], bool]) โ€“ A function that takes the same arguments as the decorated function and returns True if the precondition is satisfied.

  • message (str) โ€“ The error message to raise if the precondition fails.

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:
  • predicate (Callable[[T], bool]) โ€“ A function that takes the return value of the decorated function and returns True if the postcondition is satisfied.

  • message (str) โ€“ The error message to raise if the postcondition fails.

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: ...