API¶
Package appcore¶
Common application configuration management.
Module appcore.application¶
Information about application.
- class appcore.application.Information(*, name, publisher=None, version=None)¶
Bases:
DataclassObjectInformation about an application.
- Variables:
- produce_platform_directories()¶
Produces platform directories object for application.
- Parameters:
self
- Return type:
platformdirs.unix.Unix
Module appcore.distribution¶
Information about package distribution.
- class appcore.distribution.Information(*, name, location, editable)¶
Bases:
DataclassObjectInformation about a package distribution.
- Variables:
name (str)
location (pathlib.Path)
editable (bool)
- async classmethod prepare(exits, anchor=absence.absent, package=absence.absent)¶
Acquires information about package distribution.
- Parameters:
selfclass
exits (contextlib.AsyncExitStack)
anchor (pathlib.Path | absence.objects.AbsentSingleton)
package (str | absence.objects.AbsentSingleton)
- Return type:
typing_extensions.Self
Module appcore.configuration¶
Fundamental configuration.
- class appcore.configuration.AcquirerAbc¶
Bases:
DataclassProtocol,ProtocolAbstract base class for configuration acquirers.
- class appcore.configuration.EnablementTristate(value)¶
Bases:
EnumDisable, enable, or retain the natural state?
- Variables:
Disable (appcore.configuration.EnablementTristate)
- is_retain()¶
Does enum indicate a retain state?
- class appcore.configuration.TomlAcquirer(*, main_filename='general.toml', includes_name='includes')¶
Bases:
AcquirerAbcAcquires configuration data from TOML data files.
Module appcore.cli¶
CLI foundation classes and interfaces.
This module provides the core infrastructure for building command-line interfaces. It offers a comprehensive framework for creating CLI applications with rich presentation options, flexible output routing, and integrated logging capabilities.
Key Components¶
Command Framework¶
Command- Abstract base class for CLI command implementationsApplicationdataclass for command-line application configurationRich integration with tyro for automatic argument parsing and help generation
Display and Output Control¶
DisplayOptions- Configuration for output presentation and routingInscriptionControl- Configuration for logging and diagnostic outputStream routing (stdout/stderr) and file output capabilities
Rich terminal detection with colorization control
Example Usage¶
Basic CLI application with custom display options and subcommands:
from appcore import cli, state
class MyDisplayOptions( cli.DisplayOptions ):
format: str = 'table'
class MyGlobals( state.Globals ):
display: MyDisplayOptions
class StatusCommand( cli.Command ):
async def execute( self, auxdata: state.Globals ) -> None:
if isinstance( auxdata, MyGlobals ):
format_val = auxdata.display.format
print( f"Status: Running (format: {format_val})" )
class InfoCommand( cli.Command ):
async def execute( self, auxdata: state.Globals ) -> None:
print( f"App: {auxdata.application.name}" )
class MyApplication( cli.Application ):
display: MyDisplayOptions = __.dcls.field(
default_factory = MyDisplayOptions )
command: __.typx.Union[
__.typx.Annotated[
StatusCommand,
_tyro.conf.subcommand( 'status', prefix_name = False ),
],
__.typx.Annotated[
InfoCommand,
_tyro.conf.subcommand( 'info', prefix_name = False ),
],
] = __.dcls.field( default_factory = StatusCommand )
async def execute( self, auxdata: state.Globals ) -> None:
await self.command( auxdata )
async def prepare( self, exits ) -> state.Globals:
auxdata_base = await super( ).prepare( exits )
return MyGlobals(
display = self.display, **auxdata_base.__dict__ )
- class appcore.cli.Application(*, configfile=None, environment=True, inscription=<factory>)¶
Bases:
DataclassProtocol,ProtocolCommon infrastructure and standard interface for applications.
Example:
class MyApplication( Application ): display: DisplayOptions = __.dcls.field( default_factory = DisplayOptions ) async def execute( self, auxdata: state.Globals ) -> None: print( f"Application: {auxdata.application.name}" )
- Variables:
configfile (pathlib.Path | None)
environment (bool)
inscription (appcore.cli.InscriptionControl)
- abstract async execute(auxdata)¶
Executes command.
- Parameters:
self
auxdata (appcore.state.Globals)
- async prepare(exits)¶
Prepares session context.
- Parameters:
self
exits (contextlib.AsyncExitStack)
- Return type:
- class appcore.cli.Command¶
Bases:
DataclassProtocol,ProtocolStandard interface for command implementations.
Example:
class StatusCommand( Command ): async def execute( self, auxdata: state.Globals ) -> None: print( f"Application: {auxdata.application.name}" )
- abstract async execute(auxdata)¶
Executes command.
- Parameters:
self
auxdata (appcore.state.Globals)
- async prepare(auxdata)¶
Prepares session context.
- Parameters:
self
auxdata (appcore.state.Globals)
- Return type:
- class appcore.cli.DisplayOptions(*, colorize=True, target_file=None, target_stream=TargetStreams.Stdout, assume_rich_terminal=False)¶
Bases:
DataclassObjectStandardized display configuration for CLI applications.
Example:
class MyDisplayOptions( DisplayOptions ): format: str = 'table' compact: bool = False
- Variables:
colorize (bool)
target_file (pathlib.Path | None)
target_stream (appcore.cli.TargetStreams | None)
assume_rich_terminal (bool)
- determine_colorization(stream)¶
Determines whether to use colorized output.
- async provide_stream(exits)¶
Provides target stream from options.
- Parameters:
self
exits (contextlib.AsyncExitStack)
- Return type:
- class appcore.cli.InscriptionControl(*, level='info', presentation=Presentations.Plain, target_file=None, target_stream=TargetStreams.Stderr)¶
Bases:
DataclassObjectInscription (logging, debug prints) control.
- Variables:
level (Literal[ 'debug', 'info', 'warn', 'error', 'critical' ])
presentation (appcore.inscription.Presentations)
target_file (pathlib.Path | None)
target_stream (appcore.cli.TargetStreams | None)
- as_control(exits)¶
Produces compatible inscription control for appcore.
- Parameters:
self
exits (contextlib.AsyncExitStack)
- Return type:
Module appcore.introspection¶
Application for configuration introspection.
This module provides a complete CLI application for introspecting
configuration, environment variables, and platform directories. It serves
as both a practical utility and a comprehensive example of building CLI
applications with the appcore.cli framework.
Command-Line Interface¶
The appcore command provides three main introspection capabilities:
Configuration Inspection¶
Display finalized application configuration from TOML files:
appcore configuration # Default rich format
appcore --display.presentation json configuration
appcore --display.presentation toml configuration
Environment Variables¶
Show application-specific environment variables:
appcore environment # All APPCORE_* variables
appcore --display.presentation plain environment
Platform Directories¶
Display platform-specific directories for the application:
appcore directories # Show all directory paths
appcore --display.target-file dirs.txt directories
Presentation Formats¶
Multiple output formats are supported through the presentation option:
rich(default) - Rich formatted output with syntax highlightingjson- JSON format for programmatic consumptiontoml- TOML format matching input configuration filesplain- Plain text format for simple displays
Output Routing¶
Flexible output destinations:
Stream Routing¶
--display.target-stream stdout(default) - Main output to stdout--display.target-stream stderr- Main output to stderr--inscription.target-stream stderr(default) - Logging to stderr--inscription.target-stream stdout- Logging to stdout
File Output¶
--display.target-file path- Save main output to file--inscription.target-file path- Save logging to file
Terminal Control¶
Rich terminal behavior can be controlled:
--display.colorize/--display.no-colorize- Control colorization--display.assume-rich-terminal- Force Rich capabilities (testing)
Implementation Architecture¶
Command Structure¶
IntrospectConfigurationCommand- Configuration introspectionIntrospectEnvironmentCommand- Environment variable inspectionIntrospectDirectoriesCommand- Platform directories inspectionApplicationGlobals- Extended state for CLI context
Usage as Implementation Example¶
This module demonstrates comprehensive CLI application patterns:
Command inheritance from
appcore.cli.CommandAsync execution with proper error handling
Integration with appcore preparation and configuration systems
File and stream output routing capabilities
Rich terminal integration with automatic capability detection
The source code serves as a reference implementation for building similar CLI applications with the appcore framework.
- class appcore.introspection.Application(*, configfile=None, environment=True, inscription=<factory>, display=<factory>, command=<factory>)¶
Bases:
ApplicationApplication for introspection of configuration.
- Variables:
configfile (pathlib.Path | None)
environment (bool)
inscription (appcore.cli.InscriptionControl)
display (appcore.introspection.DisplayOptions)
command (appcore.introspection.IntrospectConfigurationCommand | appcore.introspection.IntrospectEnvironmentCommand | appcore.introspection.IntrospectDirectoriesCommand)
- async execute(auxdata)¶
- Parameters:
self
auxdata (appcore.state.Globals)
- async prepare(exits)¶
- Parameters:
self
exits (contextlib.AsyncExitStack)
- Return type:
- class appcore.introspection.ApplicationGlobals(*, application, configuration, directories, distribution, exits, display=<factory>)¶
Bases:
GlobalsIncludes display options.
- Variables:
application (appcore.application.Information)
configuration (accretive.dictionaries.Dictionary[ str, typing_extensions.Any ])
directories (platformdirs.unix.Unix)
distribution (appcore.distribution.Information)
exits (contextlib.AsyncExitStack)
display (appcore.introspection.DisplayOptions)
- class appcore.introspection.DisplayOptions(*, colorize=True, target_file=None, target_stream=TargetStreams.Stdout, assume_rich_terminal=False, presentation=Presentations.Rich)¶
Bases:
DisplayOptionsDisplay options, including presentation mode.
- Variables:
colorize (bool)
target_file (pathlib.Path | None)
target_stream (appcore.cli.TargetStreams | None)
assume_rich_terminal (bool)
presentation (appcore.introspection.Presentations)
- async render(data)¶
Renders data according to display options.
- Parameters:
self
data (typing_extensions.Any)
- class appcore.introspection.IntrospectConfigurationCommand¶
Bases:
CommandShows finalized application configuration.
- async execute(auxdata)¶
- Parameters:
self
auxdata (appcore.state.Globals)
- class appcore.introspection.IntrospectDirectoriesCommand¶
Bases:
CommandShows application and package directories.
- async execute(auxdata)¶
- Parameters:
self
auxdata (appcore.state.Globals)
- class appcore.introspection.IntrospectEnvironmentCommand¶
Bases:
CommandShows application-specific environment variables.
- async execute(auxdata)¶
- Parameters:
self
auxdata (appcore.state.Globals)
- class appcore.introspection.Presentations(value)¶
Bases:
EnumPresentation mode (format) for CLI output.
- appcore.introspection.execute_cli()¶
Synchronous entrypoint.
Module appcore.state¶
Immutable global state.
- class appcore.state.DirectorySpecies(value)¶
Bases:
EnumPossible species for locations.
- Variables:
Cache (appcore.state.DirectorySpecies)
State (appcore.state.DirectorySpecies)
- class appcore.state.Globals(*, application, configuration, directories, distribution, exits)¶
Bases:
DataclassObjectImmutable global data. Required by some library functions.
- Variables:
application (appcore.application.Information)
configuration (accretive.dictionaries.Dictionary[ str, typing_extensions.Any ])
directories (platformdirs.unix.Unix)
distribution (appcore.distribution.Information)
exits (contextlib.AsyncExitStack)
- as_dictionary()¶
Returns shallow copy of state.
- Parameters:
self
- Return type:
collections.abc.Mapping[ str, typing_extensions.Any ]
- provide_cache_location(*appendages)¶
Provides cache location from configuration.
- Parameters:
self
appendages (str)
- Return type:
- provide_data_location(*appendages)¶
Provides data location from configuration.
- Parameters:
self
appendages (str)
- Return type:
- provide_location(species, *appendages)¶
Provides particular species of location from configuration.
- Parameters:
self
species (appcore.state.DirectorySpecies)
appendages (str)
- Return type:
Module appcore.inscription¶
Application inscription management.
Logging and, potentially, debug printing.
- type appcore.inscription.Target = _io.TextIOWrapper | TextIO | appcore.inscription.TargetDescriptor¶
- class appcore.inscription.Control(*, mode=Presentations.Plain, level='info', target=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>)¶
Bases:
DataclassObjectApplication inscription configuration.
- Variables:
level (Literal[ 'debug', 'info', 'warn', 'error', 'critical' ])
target (_io.TextIOWrapper | TextIO | appcore.inscription.TargetDescriptor)
- appcore.inscription.Modes¶
alias of
Presentations
- class appcore.inscription.TargetDescriptor(*, location, mode=TargetModes.Truncate, codec='utf-8')¶
Bases:
DataclassObjectDescriptor for file-based inscription targets.
- Variables:
location (bytes | str | os.PathLike[ bytes ] | os.PathLike[ str ])
codec (str)
- class appcore.inscription.TargetModes(value)¶
Bases:
EnumTarget file mode control.
- Variables:
Append (appcore.inscription.TargetModes)
Truncate (appcore.inscription.TargetModes)
- appcore.inscription.prepare(auxdata, /, control)¶
Prepares various scribes in a sensible manner.
- Parameters:
auxdata (appcore.state.Globals)
control (appcore.inscription.Control)
Module appcore.preparation¶
Preparation of the application core.
- async appcore.preparation.prepare(exits, acquirer=TomlAcquirer(main_filename='general.toml', includes_name='includes'), application=absence.absent, configedits=(), configfile=absence.absent, directories=absence.absent, distribution=absence.absent, environment=False, inscription=absence.absent)¶
Prepares globals DTO to pass through application.
Also: * Optionally, configures logging for application * Optionally, loads process environment from files.
Note that asynchronous preparation allows for applications to concurrently initialize other entities outside of the library, even though the library initialization, itself, is inherently sequential.
- Parameters:
exits (contextlib.AsyncExitStack)
acquirer (appcore.configuration.AcquirerAbc)
application (appcore.application.Information | absence.objects.AbsentSingleton)
configedits (collections.abc.Iterable[ appcore.dictedits.Edit ])
configfile (pathlib.Path | io.TextIOBase | absence.objects.AbsentSingleton)
directories (platformdirs.unix.Unix | absence.objects.AbsentSingleton)
distribution (appcore.distribution.Information | absence.objects.AbsentSingleton)
environment (bool | collections.abc.Mapping[ str, typing_extensions.Any ])
inscription (appcore.inscription.Control | absence.objects.AbsentSingleton)
- Return type:
Module appcore.exceptions¶
Family of exceptions for package API.
This module defines a comprehensive exception hierarchy for the appcore library, providing specific exception types for different failure modes while maintaining a consistent interface for error handling and debugging.
Exception Hierarchy¶
The exception hierarchy follows a two-tier design:
Omniexception- Base for all package exceptionsOmnierror- Base for error exceptions, inherits from bothOmniexceptionandException
Usage¶
Catch all package errors with Omnierror or with built-in exception
types. See class inheritance for details.
- exception appcore.exceptions.AddressLocateFailure(subject, address, part)¶
Bases:
Omnierror,LookupErrorFailure to locate address.
- exception appcore.exceptions.AsyncAssertionFailure(entity)¶
Bases:
Omnierror,AssertionError,TypeErrorAssertion of awaitability of entity failed.
- exception appcore.exceptions.ContextInvalidity(auxdata)¶
Bases:
Omnierror,TypeError,ValueError
- exception appcore.exceptions.DependencyAbsence(dependency, feature)¶
Bases:
Omnierror,ImportError
- exception appcore.exceptions.EntryAssertionFailure(subject, name)¶
Bases:
Omnierror,AssertionError,KeyErrorAssertion of entry in dictionary failed.
- exception appcore.exceptions.FileLocateFailure(subject, name)¶
Bases:
Omnierror,FileNotFoundErrorFailure to locate file.
- exception appcore.exceptions.Omnierror(*posargs, **nomargs)¶
Bases:
Omniexception,ExceptionBase for error exceptions raised by package API.
- exception appcore.exceptions.Omniexception(*posargs, **nomargs)¶
Bases:
Object,BaseExceptionBase for all exceptions raised by package API.
- exception appcore.exceptions.OperationInvalidity(subject, name)¶
Bases:
Omnierror,RuntimeErrorInvalid operation.
Module appcore.generics¶
Generic types.
- type appcore.generics.GenericResult = appcore.generics.Result[typing_extensions.Any, Exception]¶
- class appcore.generics.Error(error)¶
Bases:
Result[T,E]Result of failed computation.
- Variables:
error (appcore.generics.E)
- extract()¶
- Parameters:
self
- Return type:
typing_extensions.Never
- transform(function)¶
- Parameters:
self
function (collections.abc.Callable[ [ appcore.generics.T ], appcore.generics.U ])
- Return type:
typing_extensions.Self
- class appcore.generics.Result(*posargs, **nomargs)¶
Bases:
Protocol,Generic[T,E]Either a value or an error.
- abstract extract()¶
Extracts value from result. Else, raises error from result.
Similar to Result.unwrap in Rust.
- Parameters:
self
- Return type:
appcore.generics.T
- abstract transform(function)¶
Transforms value in value result. Ignores error result.
Similar to Result.map in Rust.
- Parameters:
self
function (collections.abc.Callable[ [ appcore.generics.T ], appcore.generics.U ])
- Return type:
typing_extensions.Self | Result[ U, E ]
- class appcore.generics.Value(value)¶
Bases:
Result[T,E]Result of successful computation.
- Variables:
value (appcore.generics.T)
- extract()¶
- Parameters:
self
- Return type:
appcore.generics.T
- transform(function)¶
- Parameters:
self
function (collections.abc.Callable[ [ appcore.generics.T ], appcore.generics.U ])
- Return type:
Result[ U, E ]
- appcore.generics.is_error(result)¶
Type guard: Returns
Trueif result is an error.- Parameters:
result (appcore.generics.Result[ appcore.generics.T, appcore.generics.E ])
- Return type:
typing_extensions.TypeIs[ appcore.generics.Error[ appcore.generics.T, appcore.generics.E ] ]
- appcore.generics.is_value(result)¶
Type guard: Returns
Trueif result is a value.- Parameters:
result (appcore.generics.Result[ appcore.generics.T, appcore.generics.E ])
- Return type:
typing_extensions.TypeIs[ appcore.generics.Value[ appcore.generics.T, appcore.generics.E ] ]
Module appcore.io¶
Common I/O primitives.
- async appcore.io.acquire_text_file_async(file, charset='utf-8', deserializer=absence.absent)¶
Reads file asynchronously.
- Parameters:
file (str | pathlib.Path)
charset (str)
deserializer (collections.abc.Callable[ [ str ], typing_extensions.Any ] | absence.objects.AbsentSingleton)
- Return type:
typing_extensions.Any
- async appcore.io.acquire_text_files_async(*files, charset='utf-8', deserializer=absence.absent, return_exceptions=False)¶
Reads files in parallel asynchronously.
- Parameters:
files (str | pathlib.Path)
charset (str)
deserializer (collections.abc.Callable[ [ str ], typing_extensions.Any ] | absence.objects.AbsentSingleton)
return_exceptions (bool)
- Return type:
collections.abc.Sequence[ typing_extensions.Any ]
Module appcore.asyncf¶
Helper functions for async execution.
- async appcore.asyncf.gather_async(*operands, return_exceptions=False, error_message='Failure of async operations.', ignore_nonawaitables=False)¶
Gathers results from invocables concurrently and asynchronously.
- async appcore.asyncf.intercept_error_async(awaitable)¶
Converts unwinding exceptions to error results.
Exceptions, which are not instances of
Exceptionor one of its subclasses, are allowed to propagate. In particular,KeyboardInterruptandSystemExitmust be allowed to propagate to be consistent withasyncio.TaskGroupbehavior.Helpful when working with
asyncio.gather(), for example, because exceptions can be distinguished from computed values and collected together into an exception group.In general, it is a bad idea to swallow exceptions. In this case, the intent is to add them into an exception group for continued propagation.
- Parameters:
awaitable (collections.abc.Awaitable[ typing_extensions.Any ])
- Return type: