ae.base

basic constants and helper functions

this module is pure python and has no external dependencies. apart from providing base constants and common helper functions it is also patching the shutil module to prevent crashes on Android OS.

base constants

ISO format strings for date and datetime values are provided by the constants DATE_ISO and DATE_TIME_ISO.

the UNSET constant is useful in cases where None is a valid data value and another special value is needed to specify that e.g. an argument or attribute has no (valid) value or did not get specified/passed.

the string os_platform provides the OS where your app is running.

base helper functions

use env_str() to determine the value of an OS environment variable with automatic variable name conversion. other helper functions provided by this namespace portion to determine the values of the most important system environment variables for your application are sys_env_dict() and sys_env_text().

norm_line_sep() is converting any combination of line separators of a string to a single new-line character.

norm_name() converts any string into a name that can be used e.g. as file name or as method/attribute name.

camel_to_snake() and snake_to_camel() providing name conversions of class and method names.

to encode unicode strings to other codecs the functions force_encoding() and to_ascii() can be used.

the round_traditional() function get provided by this module for traditional rounding of float values. the function signature is fully compatible to Python’s round() function.

the function instantiate_config_parser() ensures that the ConfigParser instance is correctly configured, e.g. to support case-sensitive config variable names and to use ExtendedInterpolation for the interpolation argument.

Module Attributes

BUILD_CONFIG_FILE

app build config file

CFG_EXT

CFG config file extension

INI_EXT

INI config file extension

DATE_ISO

ISO string format for date values (e.g.

DATE_TIME_ISO

ISO string format for datetime values

DEF_ENCODE_ERRORS

default encode error handling for UnicodeEncodeErrors

DEF_ENCODING

encoding for force_encoding() that will always work independent from destination (console, file sys, …).

NAME_PARTS_SEP

name parts separator character, e.g.

UNSET

pseudo value used for attributes/arguments if None is needed as a valid value

os_platform

operating system / platform string (see _os_platform()).

Functions

app_name_guess()

guess/try to determine the name of the currently running app (w/o assessing not yet initialized app instance).

build_config_variable_values(*names_defaults)

determine build config variable values from the buildozer.spec file in the current directory.

camel_to_snake(name)

convert name from CamelCase to snake_case.

duplicates(values)

determine all duplicates in the passed iterable.

env_str(name[, convert_name])

determine the string value of an OS environment variable, optionally preventing invalid variable name.

force_encoding(text[, encoding, errors])

force/ensure the encoding of text (str or bytes) without any UnicodeDecodeError/UnicodeEncodeError.

instantiate_config_parser()

instantiate and prepare config file parser.

norm_line_sep(text)

convert any combination of line separators in the passed text to new-line characters.

norm_name(name)

normalize name to contain only alpha-numeric and underscore chars (e.g.

now_str([sep])

return the current timestamp as string (to use as suffix for file and variable/attribute names).

os_host_name()

determine the operating system host/machine name.

os_local_ip()

determine ip address of this system/machine in the local network (LAN or WLAN).

os_user_name()

determine the operating system user name.

round_traditional(num_value[, num_digits])

round numeric value traditional.

snake_to_camel(name[, back_convertible])

convert name from snake_case to CamelCase.

sys_env_dict()

returns dict with python system run-time environment values.

sys_env_text([ind_ch, ind_len, key_ch, …])

compile formatted text block with system environment info.

to_ascii(unicode_str)

converts unicode string into ascii representation.

BUILD_CONFIG_FILE = 'buildozer.spec'

app build config file

CFG_EXT: str = '.cfg'

CFG config file extension

INI_EXT: str = '.ini'

INI config file extension

DATE_ISO: str = '%Y-%m-%d'

ISO string format for date values (e.g. in config files/variables)

DATE_TIME_ISO: str = '%Y-%m-%d %H:%M:%S.%f'

ISO string format for datetime values

DEF_ENCODE_ERRORS: str = 'backslashreplace'

default encode error handling for UnicodeEncodeErrors

DEF_ENCODING: str = 'ascii'

encoding for force_encoding() that will always work independent from destination (console, file sys, …).

NAME_PARTS_SEP = '_'

name parts separator character, e.g. for norm_name()

class _UNSET[source]

Bases: object

(singleton) UNSET (type) object class.

__bool__()[source]

ensure to be evaluated as False, like None.

__len__()[source]

ensure to be evaluated as empty.

UNSET = <ae.base._UNSET object>

pseudo value used for attributes/arguments if None is needed as a valid value

app_name_guess()[source]

guess/try to determine the name of the currently running app (w/o assessing not yet initialized app instance).

Return type

str

Returns

application name/id or “unguessable” if not guessable.

build_config_variable_values(*names_defaults, section='app')[source]

determine build config variable values from the buildozer.spec file in the current directory.

Parameters
  • names_defaults (Tuple[str, Any]) – tuple of tuples of build config variable names and default values.

  • section (str) – name of the spec file section, using ‘app’ as default.

Return type

Tuple[Any, …]

Returns

tuple of build config variable values (using the passed default value if not specified in the BUILD_CONFIG_FILE spec file or if the spec file does not exists in cwd).

camel_to_snake(name)[source]

convert name from CamelCase to snake_case.

Parameters

name (str) – name string in snake case format.

Return type

str

Returns

name in camel case.

duplicates(values)[source]

determine all duplicates in the passed iterable.

inspired by Ritesh Kumars answer to https://stackoverflow.com/questions/9835762.

Parameters

values (Iterable) – iterable (list, tuple, str, …) to search for duplicate items.

Return type

list

Returns

list of the duplicate items found (can contain the same duplicate multiple times).

env_str(name, convert_name=False)[source]

determine the string value of an OS environment variable, optionally preventing invalid variable name.

Parameters
  • name (str) – name of a OS environment variable.

  • convert_name (bool) – pass True to prevent invalid variable names by converting CamelCase names into SNAKE_CASE, lower-case into upper-case and all non-alpha-numeric characters into underscore characters.

Return type

Optional[str]

Returns

string value of OS environment variable if found, else None.

force_encoding(text, encoding='ascii', errors='backslashreplace')[source]

force/ensure the encoding of text (str or bytes) without any UnicodeDecodeError/UnicodeEncodeError.

Parameters
Return type

str

Returns

text as str (with all characters checked/converted/replaced to be encode-able).

instantiate_config_parser()[source]

instantiate and prepare config file parser.

Return type

ConfigParser

norm_line_sep(text)[source]

convert any combination of line separators in the passed text to new-line characters.

Parameters

text (str) – string containing any combination of line separators (‘\r\n’ or ‘\r’).

Return type

str

Returns

normalized/converted string with only new-line (‘\n’) line separator characters.

norm_name(name)[source]

normalize name to contain only alpha-numeric and underscore chars (e.g. for a variable-/method-/file-name).

Parameters

name (str) – any string to be converted into a valid variable/method/file/… name.

Return type

str

Returns

cleaned/normalized/converted name string.

now_str(sep='')[source]

return the current timestamp as string (to use as suffix for file and variable/attribute names).

Parameters

sep (str) – optional prefix and separator character (separating date from time and in time part the seconds from the microseconds).

Return type

str

Returns

timestamp as string (length=20 + 3 * len(sep)).

os_host_name()[source]

determine the operating system host/machine name.

Return type

str

Returns

machine name string.

os_local_ip()[source]

determine ip address of this system/machine in the local network (LAN or WLAN).

inspired by answers of SO users @dml and @fatal_error to the question: https://stackoverflow.com/questions/166506.

Return type

str

Returns

ip address of this machine in the local network (WLAN or LAN/ethernet) or empty string if this machine is not connected to any network.

_os_platform()[source]

determine the operating system where this code is running (used to initialize the os_platform variable).

Return type

str

Returns

operating system (extension) as string:

  • ’android’ for all Android systems.

  • ’cygwin’ for MS Windows with an installed Cygwin extension.

  • ’darwin’ for all Apple Mac OS X systems.

  • ’freebsd’ for all other BSD-based unix systems.

  • ’ios’ for all Apple iOS systems.

  • ’linux’ for all other unix systems (like Arch, Debian/Ubuntu, Suse, …).

  • ’win32’ for MS Windows systems (w/o the Cygwin extension).

os_platform = 'linux'

operating system / platform string (see _os_platform()).

this string value gets determined for most of the operating systems with the help of Python’s sys.platform() function and additionally detects the operating systems iOS and Android (not supported by Python).

os_user_name()[source]

determine the operating system user name.

Return type

str

Returns

user name string.

round_traditional(num_value, num_digits=0)[source]

round numeric value traditional.

needed because python round() is working differently, e.g. round(0.075, 2) == 0.07 instead of 0.08 inspired by https://stackoverflow.com/questions/31818050/python-2-7-round-number-to-nearest-integer.

Parameters
  • num_value (float) – float value to be round.

  • num_digits (int) – number of digits to be round (def=0 - rounds to an integer value).

Return type

float

Returns

rounded value.

snake_to_camel(name, back_convertible=False)[source]

convert name from snake_case to CamelCase.

Parameters
  • name (str) – name string composed of parts separated by an underscore character (NAME_PARTS_SEP).

  • back_convertible (bool) – pass True to have lower-case character at the begin of the returned name if the snake name has no leading underscore character (and to allow the conversion between snake and camel case without information loss).

Return type

str

Returns

name in camel case.

sys_env_dict()[source]

returns dict with python system run-time environment values.

Return type

Dict[str, Any]

Returns

python system run-time environment values like python_ver, argv, cwd, executable, frozen and bundle_dir (if bundled with pyinstaller).

sys_env_text(ind_ch=' ', ind_len=12, key_ch='=', key_len=15, extra_sys_env_dict=None)[source]

compile formatted text block with system environment info.

Parameters
  • ind_ch (str) – indent character (default=” “).

  • ind_len (int) – indent depths (default=12 characters).

  • key_ch (str) – key-value separator character (default=”=”).

  • key_len (int) – key-name minimum length (default=15 characters).

  • extra_sys_env_dict (Optional[Dict[str, str]]) – dict with additional system info items.

Return type

str

Returns

text block with system environment info.

to_ascii(unicode_str)[source]

converts unicode string into ascii representation.

useful for fuzzy string compare; inspired by MiniQuark’s answer in: https://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string

Parameters

unicode_str (str) – string to convert.

Return type

str

Returns

converted string (replaced accents, diacritics, … into normal ascii characters).