Coverage for muutils/console_unicode.py: 100%

7 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-04 03:33 -0600

1import locale 

2 

3 

4def get_console_safe_str( 

5 default: str, 

6 fallback: str, 

7) -> str: 

8 """Determine a console-safe string based on the preferred encoding. 

9 

10 This function attempts to encode a given `default` string using the system's preferred encoding. 

11 If encoding is successful, it returns the `default` string; otherwise, it returns a `fallback` string. 

12 

13 # Parameters: 

14 - `default : str` 

15 The primary string intended for use, to be tested against the system's preferred encoding. 

16 - `fallback : str` 

17 The alternative string to be used if `default` cannot be encoded in the system's preferred encoding. 

18 

19 # Returns: 

20 - `str` 

21 Either `default` or `fallback` based on whether `default` can be encoded safely. 

22 

23 # Usage: 

24 

25 ```python 

26 >>> get_console_safe_str("café", "cafe") 

27 "café" # This result may vary based on the system's preferred encoding. 

28 ``` 

29 """ 

30 try: 

31 default.encode(locale.getpreferredencoding()) 

32 return default 

33 except UnicodeEncodeError: 

34 return fallback