ae.base

basic constants, helper functions and context manager

this module is pure python and has no external dependencies. apart from providing base constants, common helper functions and context managers, 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

the function duplicates() returns the duplicates of an iterable.

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().

app_name_guess() guesses the name of o running Python application from the application environment, with the help of build_config_variable_values(), which determines config-variable-values from the app’s build spec file.

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.

to normalize a file path, in order to remove ., .. placeholders, to resolve symbolic links or to make it relative or absolute, call the function norm_path().

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.

generic context manager

the context manager in_wd() changes the current working directory in the temporary context. the following example demonstrate a typical usage, together with a temporary path, created with the help of Pythons TemporaryDirectory class:

with tempfile.TemporaryDirectory() as tmp_dir, in_wd(tmp_dir):
    assert os.getcwd() == tmp_dir
    # the tmp_dir is set as the current working directory
# current working directory set back to the original path and the temporary directory got removed

Module Attributes

DOCS_FOLDER

project documentation root folder name

TESTS_FOLDER

name of project folder to store unit/integration tests

TEMPLATES_FOLDER

template folder name, used in template and namespace root projects to maintain and provide common file templates

BUILD_CONFIG_FILE

gui app build config file

PACKAGE_INCLUDE_FILES_PREFIX

prefix of file/folder names to be included into the package_data

PY_EXT

file extension for modules and hooks

PY_INIT

init-module file name of a python package

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.

in_wd(new_cwd)

context manager to temporary switch the current working directory / cwd.

instantiate_config_parser()

instantiate and prepare config file parser.

main_file_paths_parts(portion_name)

determine tuple of supported main/version file name path part tuples.

norm_line_sep(text)

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

norm_name(name[, allow_num_prefix])

normalize name to start with a letter/alphabetic/underscore and to contain only alpha-numeric/underscore chars.

norm_path(path[, make_absolute, …])

normalize path, replacing ../. parts or the tilde character (for home folder) and transform to relative/abs.

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.

project_main_file(import_name[, project_path])

determine the main module file path of a package project, containing the package __version__ module variable.

read_file(file_path[, extra_mode, encoding, …])

returning content of the text/binary file specified by file_path argument as string.

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.

write_file(file_path, content[, extra_mode, …])

(over)write the file specified by file_path with text or binary/bytes content.

Classes

UnsetType()

(singleton) UNSET (type) object class.

DOCS_FOLDER = 'docs'

project documentation root folder name

TESTS_FOLDER = 'tests'

name of project folder to store unit/integration tests

TEMPLATES_FOLDER = 'templates'

template folder name, used in template and namespace root projects to maintain and provide common file templates

BUILD_CONFIG_FILE = 'buildozer.spec'

gui app build config file

PACKAGE_INCLUDE_FILES_PREFIX = 'ae_'

prefix of file/folder names to be included into the package_data

PY_EXT = '.py'

file extension for modules and hooks

PY_INIT = '__init__.py'

init-module file name of a python package

CFG_EXT = '.cfg'

CFG config file extension

INI_EXT = '.ini'

INI config file extension

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

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

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

ISO string format for datetime values

DEF_ENCODE_ERRORS = 'backslashreplace'

default encode error handling for UnicodeEncodeErrors

DEF_ENCODING = '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 UnsetType[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.UnsetType 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 CamelCaseFormat.

Return type

str

Returns

name in snake_case_format.

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

in_wd(new_cwd)[source]

context manager to temporary switch the current working directory / cwd.

Parameters

new_cwd (str) – path to the directory to switch to (within the context/with block).

Return type

Generator[None, None, None]

main_file_paths_parts(portion_name)[source]

determine tuple of supported main/version file name path part tuples.

Parameters

portion_name (str) – portion or package name.

Return type

Tuple[Tuple[str, …], …]

Returns

tuple of tuples of main/version file name path parts.

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, allow_num_prefix=False)[source]

normalize name to start with a letter/alphabetic/underscore and to contain only alpha-numeric/underscore chars.

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

  • allow_num_prefix (bool) – pass True to allow leading digits in the returned normalized name.

Return type

str

Returns

cleaned/normalized/converted name string (e.g. for a variable-/method-/file-name).

norm_path(path, make_absolute=True, remove_base_path='', remove_dots=True, resolve_sym_links=True)[source]

normalize path, replacing ../. parts or the tilde character (for home folder) and transform to relative/abs.

Parameters
  • path (str) – path string to normalize/transform.

  • make_absolute (bool) – pass False to not convert path to an absolute path.

  • remove_base_path (str) – pass a valid base path to return a relative path, even if the argument values of make_absolute or resolve_sym_links are True.

  • remove_dots (bool) – pass False to not replace/remove the . and .. placeholders.

  • resolve_sym_links (bool) – pass False to not resolve symbolic links, passing True implies a True value also for the make_absolute argument.

Return type

str

Returns

normalized path string: absolute if remove_base_path is empty and either make_absolute or resolve_sym_links is True; relative if remove_base_path is a base path of path or if path got passed as relative path and neither make_absolute nor resolve_sym_links is True.

Hint

the normalize() function additionally replaces PATH_PLACEHOLDERS.

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.

project_main_file(import_name, project_path='')[source]

determine the main module file path of a package project, containing the package __version__ module variable.

Parameters
  • import_name (str) – import name of the module/package (including namespace prefixes for namespace packages).

  • project_path (str) – optional path where the project of the package/module is situated. not needed if the current working directory is the root folder of either the import_name project or of a sister project (under the same project parent folder).

Return type

str

Returns

absolute file path/name of main module or empty string if no main/version file found.

read_file(file_path, extra_mode='', encoding=None, error_handling='ignore')[source]

returning content of the text/binary file specified by file_path argument as string.

Parameters
  • file_path (str) – file path/name to load into a string or a bytes array.

  • extra_mode (str) – extra open mode flag characters appended to “r” onto open() mode argument. pass “b” to read the content of a binary file returned as bytes array. in binary mode the argument passed in error_handling will be ignored.

  • encoding (Optional[str]) – encoding used to load and convert/interpret the file content.

  • error_handling (str) – for files opened in text mode pass ‘strict’ or None to return None (instead of an empty string) for the cases where either a decoding ValueError exception or any OSError, FileNotFoundError or PermissionError exception got raised. the default value ‘ignore’ will ignore any decoding errors (missing some characters) and will return an empty string on any file/os exception. this parameter will be ignored if the extra_mode argument contains the ‘b’ character (to read the file content as binary/bytes-array).

Return type

AnyStr

Returns

file content string or bytes array.

Raises
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).

write_file(file_path, content, extra_mode='', encoding=None)[source]

(over)write the file specified by file_path with text or binary/bytes content.

Parameters
  • file_path (str) – file path/name to write the passed content into (overwriting any previous content!).

  • content (AnyStr) – new file content either passed as string or list of line strings (will be concatenated with the line separator of the current OS: os.linesep).

  • extra_mode (str) – extra open mode flag characters appended to “w” onto open() mode argument.

  • encoding (Optional[str]) – encoding used to write/convert/interpret the file content to write.

Raises