Enasis Network Common Library#

Documentation Welcome#

Welcome to the project documentation. Below you will find the most common functions and classes within the library, but you may click your way further into the project from there. You can also view the source code.

Configuration Container#

class encommon.config.Config(files: PATHABLE | None = None, *, paths: PATHABLE | None = None, cargs: dict[str, Any] | None = None, sargs: dict[str, Any] | None = None, valid: Callable | None = None)[source]#

Bases: object

Contain the configurations from the arguments and files.

Note

Configuration loaded from files is validated with the Pydantic model encommon.config.Params.

Example#

>>> config = Config()
>>> config.config
{'enconfig': None, 'encrypts': None, 'enlogger': None}
param files:

Complete or relative path to config files.

param paths:

Complete or relative path to config paths.

param cargs:

Configuration arguments in dictionary form, which will override contents from the config files.

param sargs:

Additional arguments on the command line.

param valid:

Override default config validation model.

property files: ConfigFiles#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property paths: ConfigPaths#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property cargs: dict[str, Any]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property sargs: dict[str, Any]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property basic: dict[str, Any]#

Return the configuration source loaded from the objects.

Returns:

Configuration source loaded from the objects.

property merge: dict[str, Any]#

Return the configuration source loaded from the objects.

Returns:

Configuration source loaded from the objects.

property valid: Callable#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property params: Params#

Return the Pydantic model containing the configuration.

Returns:

Pydantic model containing the configuration.

property config: dict[str, Any]#

Return the configuration dumped from the Pydantic model.

Returns:

Configuration dumped from the Pydantic model.

property logger: Logger#

Initialize the Python logging library using parameters.

Returns:

Instance of Python logging library created.

property crypts: Crypts#

Initialize the encryption instance using the parameters.

Returns:

Instance of the encryption instance created.

property jinja2: Jinja2#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

class encommon.config.ConfigFile(path: str | Path)[source]#

Bases: object

Contain the configuration content from filesystem path.

Parameters:

path – Complete or relative path to configuration.

path: Path#
config: dict[str, Any]#
class encommon.config.ConfigFiles(paths: PATHABLE, force: bool = False)[source]#

Bases: object

Enumerate files and store the contents on relative path.

Note

Class can be empty in order to play nice with parent.

Parameters:
  • paths – Complete or relative path to config files.

  • force – Force the merge on earlier files by later.

paths: tuple[Path, ...]#
config: dict[str, ConfigFile]#
property merge: dict[str, Any]#

Return the configuration in dictionary format for files.

Returns:

Configuration in dictionary format for files.

class encommon.config.ConfigParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

paths

list[str] | None

No

None

min_length=1

paths: Annotated[list[str] | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Location of configuration files', metadata=[MinLen(min_length=1)])]#
class encommon.config.ConfigPath(path: str | Path)[source]#

Bases: object

Contain the configuration content from filesystem path.

Parameters:

path – Complete or relative path to configuration.

path: Path#
config: dict[str, ConfigFile]#
class encommon.config.ConfigPaths(paths: PATHABLE, force: bool = False)[source]#

Bases: object

Enumerate paths and store the contents on relative path.

Note

Class can be empty in order to play nice with parent.

Parameters:
  • paths – Complete or relative path to config paths.

  • force – Force the merge on earlier files by later.

paths: tuple[Path, ...]#
config: dict[str, ConfigPath]#
property merge: dict[str, Any]#

Return the configuration in dictionary format for paths.

Returns:

Configuration in dictionary format for paths.

class encommon.config.Logger(params: LoggerParams | None = None, *, stdo_level: Literal['critical', 'debug', 'error', 'info', 'warning'] | None = None, file_level: Literal['critical', 'debug', 'error', 'info', 'warning'] | None = None, file_path: str | Path | None = None)[source]#

Bases: object

Manage the file and standard output with logging library.

Note

Uses keyword name for levels in Pyton logging library.

Numeric

Keyword

10

debug

20

info

30

warning

40

error

50

critical

Example#

>>> logger = Logger(stdo_level='info')
>>> logger.start()
>>> logger.log_i(message='testing')
param stdo_level:

Minimum level for the message to pass.

param file_level:

Minimum level for the message to pass.

param file_path:

Enables writing to the filesystem path.

param params:

Parameters used to instantiate the class.

property params: LoggerParams#

Return the Pydantic model containing the configuration.

Returns:

Pydantic model containing the configuration.

property stdo_level: Literal['critical', 'debug', 'error', 'info', 'warning'] | None#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property file_level: Literal['critical', 'debug', 'error', 'info', 'warning'] | None#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property file_path: Path | None#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property started: bool#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property logger_stdo: Logger#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property logger_file: Logger#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

start() None[source]#

Initialize the Python logging library using parameters.

stop() None[source]#

Deinitialize the Python logging library using parameters.

log(level: Literal['critical', 'debug', 'error', 'info', 'warning'], *, exc_info: Exception | None = None, **kwargs: Any) None[source]#

Prepare keyword arguments and log to configured output.

Parameters:
  • exc_info – Optional exception included with trace.

  • kwargs – Keyword arguments for populating message.

log_c(**kwargs: Any) None[source]#

Prepare keyword arguments and log to configured output.

Parameters:

kwargs – Keyword arguments for populating message.

log_d(**kwargs: Any) None[source]#

Prepare keyword arguments and log to configured output.

Parameters:

kwargs – Keyword arguments for populating message.

log_e(**kwargs: Any) None[source]#

Prepare keyword arguments and log to configured output.

Parameters:

kwargs – Keyword arguments for populating message.

log_i(**kwargs: Any) None[source]#

Prepare keyword arguments and log to configured output.

Parameters:

kwargs – Keyword arguments for populating message.

log_w(**kwargs: Any) None[source]#

Prepare keyword arguments and log to configured output.

Parameters:

kwargs – Keyword arguments for populating message.

class encommon.config.LoggerParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

file_level

Literal[‘critical’, ‘debug’, ‘error’, ‘info’, ‘warning’] | None

No

None

min_length=1

file_path

str | None

No

None

min_length=1

stdo_level

Literal[‘critical’, ‘debug’, ‘error’, ‘info’, ‘warning’] | None

No

None

min_length=1

stdo_level: Annotated[Literal['critical', 'debug', 'error', 'info', 'warning'] | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Minimum logging message level', metadata=[MinLen(min_length=1)])]#
file_level: Annotated[Literal['critical', 'debug', 'error', 'info', 'warning'] | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Minimum logging message level', metadata=[MinLen(min_length=1)])]#
file_path: Annotated[str | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Enable output to the log file', metadata=[MinLen(min_length=1)])]#
class encommon.config.Message(level: Literal['critical', 'debug', 'error', 'info', 'warning'], time: PARSABLE | None = None, **kwargs: Any)[source]#

Bases: object

Format the provided keyword arguments for logging output.

Note

Log messages are expected to contain string or numeric.

Example#

>>> message = Message('info', '1970-01-01', foo='bar')
>>> strip_ansi(message.stdo_output)
'level="info" time="1970-01-01T00:00:00Z" foo="bar"'
param level:

Severity which log message is classified.

param time:

What time the log message actually occurred.

param kwargs:

Keyword arguments for populating message.

property level: Literal['critical', 'debug', 'error', 'info', 'warning']#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property time: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property fields: dict[str, str]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property stdo_output: str#

Format keyword arguments for writing to standard output.

Returns:

String representation for the standard output.

property file_output: str#

Format keyword arguments for writing to filesystem path.

Returns:

String representation for the filesystem path.

class encommon.config.Params[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

enconfig

ConfigParams | None

No

None

encrypts

CryptsParams | None

No

None

enlogger

LoggerParams | None

No

None

enconfig: Annotated[ConfigParams | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Parameters for Config instance')]#
enlogger: Annotated[LoggerParams | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Parameters for Logger instance')]#
encrypts: Annotated[CryptsParams | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Parameters for Crypts instance')]#
encommon.config.config_load(path: str | Path) dict[str, Any][source]#

Load configuration using the directory or file provided.

Parameters:

path – Complete or relative path to configuration.

Returns:

New resolved filesystem path object instance.

encommon.config.config_path(path: str | Path) Path[source]#

Resolve the provided path replacing the magic keywords.

Note

This function simply wraps one from utils subpackage.

Parameters:

path – Complete or relative path for processing.

Returns:

New resolved filesystem path object instance.

encommon.config.config_paths(paths: PATHABLE) tuple[Path, ...][source]#

Resolve the provided paths replacing the magic keywords.

Note

This function simply wraps one from utils subpackage.

Parameters:

paths – Complete or relative paths for processing.

Returns:

New resolved filesystem path object instances.

Color Formatting#

class encommon.colors.Color(source: str)[source]#

Bases: object

Covert colors to various forms using provided hex value.

Example#

>>> color = Color('#003333')
>>> color.rgb
(0, 51, 51)
>>> color.hsl
(180, 100, 10)
>>> color.xyz
(1.7814, 2.6067, 3.5412)
>>> color.xy
(0.2247, 0.3287)

Example#

>>> color1 = Color('#003333')
>>> color2 = Color('#330000')
>>> color1 - color2
Color('#32CCCD')
>>> color1 + color2
Color('#333333')
param source:

Source color used when converting values.

classmethod from_hsl(hue: int, sat: int, lev: int) Color[source]#

Initialize instance for class using provided parameters.

classmethod from_rgb(red: int, green: int, blue: int) Color[source]#

Initialize instance for class using provided parameters.

property source: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property rgb: tuple[int, int, int]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property xyz: tuple[float, float, float]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property xy: tuple[float, float]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property hsl: tuple[int, int, int]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

Encryption Decryption#

class encommon.crypts.Crypts(params: CryptsParams | None = None)[source]#

Bases: object

Encrypt and decrypt values using passphrase dictionary.

Example#

>>> phrase = Crypts.keygen()
>>> source = {'default': {'phrase': phrase}}
>>> params = CryptsParams(phrases=source)
>>> crypts = Crypts(params)
>>> encrypt = crypts.encrypt('example')
>>> encrypt
'$ENCRYPT;1.0;default;...
>>> crypts.decrypt(encrypt)
'example'
param params:

Parameters used to instantiate the class.

property params: CryptsParams#

Return the Pydantic model containing the configuration.

Returns:

Pydantic model containing the configuration.

encrypt(value: str, unique: str = 'default') str[source]#

Encrypt the provided value with the relevant passphrase.

Parameters:
  • value – String value that will returned encrypted.

  • unique – Unique identifier of mapping passphrase.

Returns:

Encrypted value using the relevant passphrase.

decrypt(value: str) str[source]#

Decrypt the provided value with the relevant passphrase.

Parameters:

value – String value that will returned decrypted.

Returns:

Decrypted value using the relevant passphrase.

create(unique: str, params: CryptParams) None[source]#

Create a new phrase using the provided input parameters.

Parameters:
  • unique – Unique identifier of mapping passphrase.

  • params – Parameters used to instantiate the class.

delete(unique: str) None[source]#

Delete the phrase from the internal dictionary reference.

Parameters:

unique – Unique identifier of mapping passphrase.

classmethod keygen() str[source]#

Return new randomly generated Fernet key for passphrase.

Returns:

Randomly generated Fernet key for passphrase.

class encommon.crypts.CryptsParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

phrases

dict[str, CryptParams]

Yes

min_length=0

phrases: Annotated[dict[str, CryptParams], FieldInfo(annotation=NoneType, required=True, description='Passphrases for the operations', metadata=[MinLen(min_length=0)])]#
class encommon.crypts.Hashes(string: str)[source]#

Bases: object

Create hash values using the provided at instantiation.

Example#

>>> hashes = Hashes('string')
>>> hashes.sha256
'473287f8298dba7163a897908958f7c0ea...

Example#

>>> hashes = Hashes('string')
>>> hashes.uuid
'38ffd1ed-2b4d-3c84-ae45-bf3bf354eee4'
param string:

String which will be used within hashing.

property string: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property md5: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property sha1: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property sha256: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property sha512: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property uuid: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property apache: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

Parsing and Manipulation#

class encommon.parse.Jinja2(statics: dict[str, Any] | None = None, filters: dict[str, Callable[[...], Any]] | None = None)[source]#

Bases: object

Parse the provided input and intelligently return value.

Example#

>>> jinja2 = Jinja2()
>>> jinja2.parse('{{ 0 | Time }}')
'1970-01-01T00:00:00.000000+0000'
param statics:

Additional values available for parsing.

param filters:

Additional filter functions for parsing.

property statics: dict[str, Any]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property filters: dict[str, Callable[[...], Any]]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property jinjenv: Environment#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

parser(value: str, statics: dict[str, Any] | None = None) Any[source]#

Return the provided input using the Jinja2 environment.

Parameters:
  • value – Input that will be processed and returned.

  • statics – Additional values available for parsing.

Returns:

Provided input using the Jinja2 environment.

parse(value: Any, statics: dict[str, Any] | None = None, literal: bool = True) Any[source]#

Return the provided input using the Jinja2 environment.

Parameters:
  • value – Input that will be processed and returned.

  • statics – Additional values available for parsing.

  • literal – Determine if Python objects are evaled.

Returns:

Provided input using the Jinja2 environment.

set_static(key: str, value: Any | None = None) None[source]#

Simply add the provided static into internal reference.

Parameters:
  • key – Where item will be inserted into reference.

  • value – Item that will be inserted into internal.

set_filter(key: str, value: Callable[[...], Any] | None = None) None[source]#

Simply add the provided filter into internal reference.

Parameters:
  • key – Where item will be inserted into reference.

  • value – Item that will be inserted into internal.

class encommon.parse.Network(source: str)[source]#

Bases: object

Convert the network into the various supported formats.

Parameters:

source – Network IPv4 or IPv6 network or address.

property source: IPNetwork#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property version: int#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property cidr: int#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property address: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property address_cidr: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property address_host: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property network: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property network_cidr: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property broadcast: str | None#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property padded: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property reverse: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property hwaddr: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property netmask: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property ispublic: bool#

Return the boolean indicating whether instance is state.

property isprivate: bool#

Return the boolean indicating whether instance is state.

property islinklocal: bool#

Return the boolean indicating whether instance is state.

property islocalhost: bool#

Return the boolean indicating whether instance is state.

encommon.parse.insubnet_ip(address: str, networks: str | list[str] | tuple[str, ...]) bool[source]#

Return the boolean indicating address is in the network.

Parameters:
  • address – Provided address to find in the network.

  • network – Networks which values can be within any.

Returns:

Boolean indicating address is in the network.

encommon.parse.isvalid_ip(value: Any) bool[source]#

Return the boolean indicating whether the value is valid.

Parameters:

value – Value that will be validated by function.

Returns:

Boolean indicating whether the value is valid.

encommon.parse.isvalid_uuid(value: Any) bool[source]#

Return the boolean indicating whether the value is valid.

Parameters:

value – Value that will be validated by function.

Returns:

Boolean indicating whether the value is valid.

Advanced Time Structures#

class encommon.times.Duration(seconds: int | float, smart: bool = True, groups: int = 7)[source]#

Bases: object

Convert the provided seconds in a human friendly format.

Example: Common Methods#

>>> durate = Duration(6048e4)
>>> durate.short
'1y 11mon 5d'
>>> durate.compact
'1y11mon5d'
>>> durate.verbose
'1 year, 11 months, 5 days'

Example: Dump the Units#

>>> durate = Duration(6048e4)
>>> durate.units()
{'year': 1, 'month': 11, 'day': 5}

Example: Disable Smart Seconds#

>>> durate = Duration(7201, False)
>>> durate.compact
'2h1s'
>>> durate.verbose
'2 hours, 1 second'

Example: Basic Operators#

>>> durate1 = Duration(1000)
>>> durate2 = Duration(2000)
>>> durate1 == durate2
False
>>> durate1 != durate2
True
>>> durate1 > durate2
False
>>> durate1 >= durate2
False
>>> durate1 < durate2
True
>>> durate1 <= durate2
True
>>> durate1 + durate2
3000.0
>>> durate1 - durate2
-1000.0
>>> durate2 - durate1
1000.0
param seconds:

Period in seconds that will be iterated.

param smart:

Determines if we hide seconds after minute.

param groups:

Determine the quantity of groups to show, ensuring larger units are returned before smaller.

property source: float#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property smart: bool#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property groups: int#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

units(short: bool = False) dict[Literal['year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'y', 'mon', 'w', 'd', 'h', 'm', 's'], int][source]#

Return the groups of time units with each relevant value.

Parameters:

short – Determine if we should use the short hand.

Returns:

Groups of time units with each relevant value.

property short: str#

Return the compact format determined by source duration.

Returns:

Compact format determined by source duration.

property compact: str#

Return the compact format determined by source duration.

Returns:

Compact format determined by source duration.

property verbose: str#

Return the verbose format determined by source duration.

Returns:

Verbose format determined by source duration.

class encommon.times.Timer(timer: int | float, *, start: str | int | float | datetime | Time | None = None)[source]#

Bases: object

Process and operate the timer using provided interval.

Example#

>>> timer = Timer(1)
>>> timer.ready()
False
>>> sleep(1)
>>> timer.ready()
True
param seconds:

Period of time which must pass in timer.

param started:

Override default of using current time.

property timer: float#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property time: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property since: float#

Return the seconds that have elapsed since the interval.

Returns:

Seconds that have elapsed since the interval.

property remains: float#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

ready(update: bool = True) bool[source]#

Determine whether or not the appropriate time has passed.

Parameters:

update – Determines whether or not time is updated.

Returns:

Boolean indicating whether enough time passed.

pause(update: bool = True) bool[source]#

Determine whether or not the appropriate time has passed.

Parameters:

update – Determines whether or not time is updated.

Returns:

Boolean indicating whether enough time passed.

update(value: str | int | float | datetime | Time | None = None) None[source]#

Update the timer from the provided parasable time value.

Parameters:

value – Override the time updated for timer value.

class encommon.times.TimerParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

start

str

Yes

min_length=1

timer

float

Yes

timer: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Seconds used for the interval')]#
start: Annotated[str, FieldInfo(annotation=NoneType, required=True, description='Optional value of timer start', metadata=[MinLen(min_length=1)])]#
class encommon.times.Timers(params: TimersParams | None = None, *, store: str = 'sqlite:///:memory:', table: str = 'timers', group: str = 'default')[source]#

Bases: object

Track timers on unique key determining when to proceed.

Warning

This class will use an in-memory database for cache, unless a cache file is explicity defined.

Example#

>>> source = {'one': TimerParams(timer=1)}
>>> params = TimersParams(timers=source)
>>> timers = Timers(params)
>>> timers.ready('one')
False
>>> sleep(1)
>>> timers.ready('one')
True
param params:

Parameters used to instantiate the class.

param store:

Optional database path for keeping state.

param group:

Optional override for default group name.

property params: TimersParams#

Return the Pydantic model containing the configuration.

Returns:

Pydantic model containing the configuration.

property store: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property group: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property store_table: type[TimersTable]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property store_engine: Engine#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property store_session: Session#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property children: dict[str, Timer]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

save_children() None[source]#

Save the child caches from the attribute into database.

ready(unique: str, update: bool = True) bool[source]#

Determine whether or not the appropriate time has passed.

Parameters:
  • unique – Unique identifier for the related child.

  • update – Determines whether or not time is updated.

Returns:

Boolean indicating whether enough time passed.

pause(unique: str, update: bool = True) bool[source]#

Determine whether or not the appropriate time has passed.

Parameters:
  • unique – Unique identifier for the related child.

  • update – Determines whether or not time is updated.

Returns:

Boolean indicating whether enough time passed.

select(unique: str) TimersRecord | None[source]#

Return the record from within the table in the database.

Returns:

Record from within the table in the database.

create(unique: str, params: TimerParams) Timer[source]#

Create a new timer using the provided input parameters.

Parameters:
  • unique – Unique identifier for the related child.

  • params – Parameters used to instantiate the class.

Returns:

Newly constructed instance of related class.

update(unique: str, value: str | int | float | datetime | Time | None = None) None[source]#

Update the timer from the provided parasable time value.

Parameters:
  • unique – Unique identifier for the related child.

  • value – Override the time updated for timer value.

delete(unique: str) None[source]#

Delete the timer from the internal dictionary reference.

Note

This is a graceful method, will not raise exception when the provided unique value does not exist.

Parameters:

unique – Unique identifier for the related child.

class encommon.times.TimersParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

timers

dict[str, TimerParams]

Yes

min_length=0

timers: Annotated[dict[str, TimerParams], FieldInfo(annotation=NoneType, required=True, description='Seconds used for the interval', metadata=[MinLen(min_length=0)])]#
class encommon.times.Time(source: str | int | float | datetime | Time | None = None, *, anchor: str | int | float | datetime | Time | None = None, format: str = '%Y-%m-%dT%H:%M:%S.%f%z', tzname: str | None = None)[source]#

Bases: object

Interact with various time functions through one wrapper.

Example#

>>> time = Time('1/1/2000 12:00am')
>>> time.stamp()
'2000-01-01T00:00:00.000000+0000'
>>> time.stamp('%m/%d/%Y')
'01/01/2000'

Example#

>>> time.epoch
946684800.0
>>> time.time
datetime.time(0, 0)
>>> time.simple
'2000-01-01T00:00:00+0000'
>>> time.human
'01/01/2000 12:00AM UTC'

Example#

>>> time.before
Time('1999-12-31T23:59:59.999999+0000')
>>> time.after
Time('2000-01-01T00:00:00.000001+0000')

Example#

>>> time.shift('-1d')
Time('1999-12-31T00:00:00.000000+0000')

Example#

>>> time.shifz('US/Central')
Time('1999-12-31T18:00:00.000000-0600')

Example#

>>> time = Time('-1s')
>>> int(time.since)
1

Example#

>>> time1 = Time('1/1/2000 12:00am')
>>> time2 = Time('1/1/2000 12:00am')
>>> time1 - time2
0.0
>>> time1 + time2
1893369600.0
param source:

Time in various forms that will be parsed.

param anchor:

Optional relative time; for snap notation.

param format:

Optional format when source is timestamp.

param tzname:

Name of the timezone associated to source. This is not relevant in timezone included in source.

property source: datetime#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property epoch: float#

Return the seconds since the Unix epoch for the instance.

Returns:

Seconds since the Unix epoch for the instance.

property spoch: int#

Return the seconds since the Unix epoch for the instance.

Returns:

Seconds since the Unix epoch for the instance.

property mpoch: float#

Return milliseconds since the Unix epoch for the instance.

Returns:

Seconds since the Unix epoch for the instance.

property time: time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property simple: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property subsec: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property human: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property elapsed: float#

Determine the time in seconds occurring since instance.

Returns:

Time in seconds occurring since the instance.

property since: float#

Determine the time in seconds occurring since instance.

Returns:

Time in seconds occurring since the instance.

property before: Time#

Return new object containing time just before the time.

Returns:

Object containing time just before the time.

property after: Time#

Return new object containing time just after the time.

Returns:

Object containing time just after the time.

stamp(format: str = '%Y-%m-%dT%H:%M:%S.%f%z', tzname: str | None = None) str[source]#

Return the timestamp using provided format for instance.

Parameters:
  • format – Optional format when source is timestamp.

  • tzname – Name of the timezone associated to source. This is not relevant in timezone included in source.

Returns:

Timestamp using provided format for instance.

shift(notate: str) Time[source]#

Return the new instance of object shifted using snaptime.

Parameters:

notate – Syntax compatable using snaptime library.

Returns:

New instance of the class using shifted time.

shifz(tzname: str) Time[source]#

Return the new instance of object shifted using datetime.

Parameters:

tzname – Name of the timezone associated to source. This is not relevant in timezone included in source.

Returns:

New instance of the class using shifted time.

class encommon.times.Window(window: str | dict[str, int], start: str | int | float | datetime | Time | None = None, stop: str | int | float | datetime | Time | None = None, *, anchor: str | int | float | datetime | Time | None = None, delay: float = 0)[source]#

Bases: object

Process and operate crontab or interval based schedule.

Example#

>>> window = Window('* * * * *', '-4m@m')
>>> [window.ready() for _ in range(6)]
[True, True, True, True, True, False]
param window:

Parameters for defining scheduled time.

param start:

Determine the start for scheduling window.

param stop:

Determine the ending for scheduling window.

param anchor:

Optionally define time anchor for window.

param delay:

Period of time schedulng will be delayed.

property window: str | dict[str, int]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property start: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property stop: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property anchor: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property delay: float#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property last: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property next: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property soonest: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property latest: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property walked: bool#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

ready(update: bool = True) bool[source]#

Walk the internal time using current position in schedule.

Parameters:

update – Determines whether or not time is updated.

Returns:

Boolean indicating outcome from the operation.

update(value: str | int | float | datetime | Time | None = None) None[source]#

Update the window from the provided parasable time value.

Parameters:

value – Override the time updated for window value.

class encommon.times.WindowParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

anchor

str | None

No

None

min_length=1

delay

float

Yes

ge=0

start

str | None

No

None

min_length=1

stop

str | None

No

None

min_length=1

window

str | dict[str, int]

Yes

min_length=1

window: Annotated[str | dict[str, int], FieldInfo(annotation=NoneType, required=True, description='Period for scheduling window', metadata=[MinLen(min_length=1)])]#
start: Annotated[str | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Determine when scope begins', metadata=[MinLen(min_length=1)])]#
stop: Annotated[str | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Determine when scope ends', metadata=[MinLen(min_length=1)])]#
anchor: Annotated[str | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Optional anchor of the window', metadata=[MinLen(min_length=1)])]#
delay: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Time period of schedule delay', metadata=[Ge(ge=0)])]#
class encommon.times.Windows(params: WindowsParams | None = None, start: str | int | float | datetime | Time = 'now', stop: str | int | float | datetime | Time = '3000-01-01', *, store: str = 'sqlite:///:memory:', table: str = 'windows', group: str = 'default')[source]#

Bases: object

Track windows on unique key determining when to proceed.

Warning

This class will use an in-memory database for cache, unless a cache file is explicity defined.

Example#

>>> source = {'one': WindowParams(window=1)}
>>> params = WindowsParams(windows=source)
>>> windows = Windows(params, '-2s', 'now')
>>> [windows.ready('one') for x in range(4)]
[True, True, True, False]
param params:

Parameters used to instantiate the class.

param start:

Determine the start for scheduling window.

param stop:

Determine the ending for scheduling window.

param store:

Optional database path for keeping state.

param group:

Optional override for default group name.

property params: WindowsParams#

Return the Pydantic model containing the configuration.

Returns:

Pydantic model containing the configuration.

property store: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property group: str#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property store_table: type[WindowsTable]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property store_engine: Engine#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property store_session: Session#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property start: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property stop: Time#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

property children: dict[str, Window]#

Return the value for the attribute from class instance.

Returns:

Value for the attribute from class instance.

save_children() None[source]#

Save the child caches from the attribute into database.

ready(unique: str, update: bool = True) bool[source]#

Determine whether or not the appropriate time has passed.

Parameters:
  • unique – Unique identifier for the related child.

  • update – Determines whether or not time is updated.

Returns:

Boolean indicating whether enough time passed.

pause(unique: str, update: bool = True) bool[source]#

Determine whether or not the appropriate time has passed.

Parameters:
  • unique – Unique identifier for the related child.

  • update – Determines whether or not time is updated.

Returns:

Boolean indicating whether enough time passed.

select(unique: str) WindowsRecord | None[source]#

Return the record from within the table in the database.

Returns:

Record from within the table in the database.

create(unique: str, params: WindowParams) Window[source]#

Create a new window using the provided input parameters.

Parameters:
  • unique – Unique identifier for the related child.

  • params – Parameters used to instantiate the class.

Returns:

Newly constructed instance of related class.

update(unique: str, value: str | int | float | datetime | Time | None = None) None[source]#

Update the window from the provided parasable time value.

Parameters:
  • unique – Unique identifier for the related child.

  • value – Override the time updated for window value.

delete(unique: str) None[source]#

Delete the window from the internal dictionary reference.

Note

This is a graceful method, will not raise exception when the provided unique value does not exist.

Parameters:

unique – Unique identifier for the related child.

class encommon.times.WindowsParams[source]#

Bases: BaseModel

Process and validate the core configuration parameters.

Fields#

Field

Type

Required

Default

Constraints

windows

dict[str, WindowParams]

Yes

min_length=0

windows: Annotated[dict[str, WindowParams], FieldInfo(annotation=NoneType, required=True, description='Period for scheduling windows', metadata=[MinLen(min_length=0)])]#
encommon.times.findtz(tzname: str | None = None) tzinfo[source]#

Return the located timezone object for the provided name.

Example#

>>> findtz('US/Central')
tzfile('/usr/share/zoneinfo/US/Central')
param tzname:

Name of the timezone associated to source.

returns:

Located timezone object for the provided name.

encommon.times.parse_time(source: str | int | float | datetime | Time | None = None, *, anchor: str | int | float | datetime | Time | None = None, format: str | None = None, tzname: str | None = None) datetime[source]#

Parse provided time value with various supported formats.

Example

Description

‘now’

Uses the current time

None, ‘None’, ‘null’

Uses the current time

‘min’, float(‘-inf’)

Uses the minimum time

‘max’, float(‘inf’)

Uses the maximum time

object

Provide datetime or Time

2000-01-01T00:00:00Z

Uses strptime and dateutil

1645843626.2

Provide Unix epoch

‘-1h@h+5m

Provide snaptime syntax

Example#

>>> parse_time('1/1/2000 12:00am')
datetime.datetime(2000, 1, 1, 0...

Example#

>>> parse_time(0)
datetime.datetime(1970, 1, 1, 0...
param source:

Time in various forms that will be parsed.

param anchor:

Optional relative time; for snap notation.

param format:

Optional format when source is timestamp.

param tzname:

Name of the timezone associated to source. This is not relevant in timezone included in source.

returns:

Python datetime object containing related time.

encommon.times.shift_time(notate: str, anchor: str | int | float | datetime | Time | None = None, *, tzname: str | None = None) datetime[source]#

Shift provided time value using snaptime relative syntax.

Example#

>>> shift_time('-1h', anchor='1/1/2000 12:00am')
datetime.datetime(1999, 12, 31, 23...

Example#

>>> shift_time('-1h@d', anchor='1/1/2000 12:00am')
datetime.datetime(1999, 12, 31, 0...
param notate:

Syntax compatable using snaptime library.

param anchor:

Optional relative time; for snap notation.

param tzname:

Name of the timezone associated to anchor. This is not relevant in timezone included in anchor.

returns:

Python datetime object containing related time.

encommon.times.since_time(start: str | int | float | datetime | Time, stop: str | int | float | datetime | Time | None = None) float[source]#

Determine the time in seconds occurring between values.

Example#

>>> start = parse_time(0)
>>> stop = parse_time(1)
>>> since_time(start, stop)
1.0
param start:

Time in various forms that will be parsed.

param stop:

Time in various forms that will be parsed.

returns:

Time in seconds occurring between the values.

encommon.times.string_time(source: str, *, formats: str | list[str] | None = None, tzname: str | None = None) datetime[source]#

Parse provided time value with various supported formats.

Example#

>>> string_time('2000-01-01T00:00:00Z')
datetime.datetime(2000, 1, 1, 0...

Example#

>>> string_time('2000/01/01')
datetime.datetime(2000, 1, 1, 0...
param source:

Time in various forms that will be parsed.

param formats:

Various formats compatable with strptime.

param tzname:

Name of the timezone associated to source. This is not relevant in timezone included in source.

returns:

Python datetime object containing related time.

encommon.times.unitime(input: int | float | str) int[source]#

Return the seconds in integer format for provided input.

Example#

>>> unitime('1d')
86400
>>> unitime('1y')
31536000
>>> unitime('1w3d4h')
878400
param input:

Input that will be converted into seconds.

returns:

Seconds in integer format for provided input.

Python Type Utilities#

class encommon.types.BaseModel[source]#

Bases: BaseModel

Pydantic base model but with added methods and routines.

Parameters:

data – Keyword arguments passed to Pydantic model.

encommon.types.clsname(cls: object) str[source]#

Return the actual definition name for the Python class.

Parameters:

cls – Provided Python class related to operation.

Returns:

Actual definition name for the Python class.

encommon.types.dedup_list(value: list[Any], update: bool = True) list[Any][source]#

Return the provided list values with duplicates removed.

Warning

This function will update the value reference.

Example#

>>> value = [1, 2, 2, 3]
>>> dedup_list(value)
[1, 2, 3]
>>> value
[1, 2, 3]
param value:

List of values processed for duplication.

param update:

Indicate if to update provided reference.

returns:

Provided list values with duplicates removed.

encommon.types.delta_dicts(dict1: dict[Any, Any], dict2: dict[Any, Any]) dict[Any, Any][source]#

Return the values in second dictionary not in the first.

Example#

>>> dict1 = {'a': 'b', 'c': [1]}
>>> dict2 = {'a': 'B', 'c': [2]}
>>> delta_dicts(dict1, dict2)
{'a': 'B', 'c': [2]}

Example#

>>> dict1 = {"x": [1, 2]}
>>> dict2 = {"x": [1]}
>>> delta_dicts(dict1, dict2)
{'x': []}
param dict1:

Primary dictionary as the source of truth.

param dict2:

Secondary dictionary finding delta values.

returns:

Values in second dictionary not in the first.

encommon.types.fuzzy_list(values: str | list[str], patterns: str | list[str]) list[str][source]#

Return the provided values that match provided patterns.

Example#

>>> values = ['foo', 'bar', 'baz', 'bop']
>>> patterns = ['*o', 'ba*']
>>> fuzzy_list(values, patterns)
['foo', 'bar', 'baz']
param values:

Value or values to enumerate for matching.

param patterns:

Patterns which values can match any one.

returns:

Provided values that match provided patterns.

encommon.types.delate(source: dict[str, Any] | list[Any], path: str, delim: str = '/') None[source]#

Delete the value within the dictionary using notation.

Example#

>>> source = {'foo': {'bar': 'baz'}}
>>> delate(source, 'foo/bar')
>>> source
{'foo': {}}
param source:

Dictionary object processed in notation.

param path:

Path to the value within the source object.

param delim:

Override default delimiter between parts.

encommon.types.expate(source: dict[str, Any], delim: str = '/') dict[str, Any][source]#

Explode the dictionary from a single depth of notation.

Example#

>>> expate({'foo/bar': 'baz'})
{'foo': {'bar': 'baz'}}
param source:

Dictionary object processed in notation.

param delim:

Override default delimiter between parts.

returns:

New dictionary that was recursively exploded.

encommon.types.funcname() str[source]#

Return the current function name where code is running.

Returns:

Current function name where code is running.

encommon.types.getate(source: tuple[Any, ...] | dict[str, Any] | list[Any], path: str, default: Any | None = None, delim: str = '/') Any[source]#

Collect the value within the dictionary using notation.

Example#

>>> source = {'foo': {'bar': 'baz'}}
>>> getate(source, 'foo/bar')
'baz'

Example#

>>> source = {'foo': ['bar', 'baz']}
>>> getate(source, 'foo/1')
'baz'
param source:

Dictionary object processed in notation.

param path:

Path to the value within the source object.

param default:

Value to use if none is found in source.

param delim:

Override default delimiter between parts.

returns:

Value that was located within provided source.

encommon.types.hasstr(haystack: str, needle: str) bool[source]#

Return the boolean indicating if needle is in haystack.

Example#

>>> haystack = 'barfoobaz'
>>> needle = 'foo'
>>> hasstr(haystack, needle)
True
param haystack:

Full string which may contain needle.

param needle:

Substring which may be within haystack.

returns:

Boolean indicating if needle is in haystack.

encommon.types.impate(source: dict[str, Any] | list[dict[str, Any]], delim: str = '/', parent: str | None = None, *, implode_list: bool = True, recurse_list: bool = True) dict[str, Any] | list[dict[str, Any]][source]#

Implode the dictionary into a single depth of notation.

Example#

>>> impate({'foo': {'bar': 'baz'}})
{'foo/bar': 'baz'}
param source:

Dictionary object processed in notation.

param delim:

Override default delimiter between parts.

param parent:

Parent key prefix for downstream update.

param implode_list:

Determine whether list is imploded.

param recurse_list:

Determine whether flatten in list.

returns:

New dictionary that was recursively imploded. It is also possible that a list of dictionary will be returned when provided and implode_list is False.

encommon.types.inlist(needle: Any, haystack: Sequence[Any]) bool[source]#

Return the boolean indicating whether needle in haystack.

Example#

>>> haystack = [1, 2, 3]
>>> inlist(2, haystack)
True
param needle:

Provided item that may be within haystack.

param haystack:

List of items which may contain needle.

returns:

Boolean indicating whether needle in haystack.

encommon.types.inrepr(needle: str, haystack: Any) bool[source]#

Return the boolean indicating if needle is in haystack.

Example#

>>> class MyClass: pass
>>> haystack = MyClass()
>>> needle = 'MyClass'
>>> inrepr(needle, haystack)
True
param needle:

Substring which may be within haystack.

param haystack:

Object which is inspected for needle.

returns:

Boolean indicating if needle is in haystack.

encommon.types.instr(needle: str, haystack: Any) bool[source]#

Return the boolean indicating if needle is in haystack.

Example#

>>> class MyClass: pass
>>> haystack = MyClass()
>>> needle = 'MyClass'
>>> instr(needle, haystack)
True
param needle:

Substring which may be within haystack.

param haystack:

Object which is inspected for needle.

returns:

Boolean indicating if needle is in haystack.

encommon.types.lattrs(cls: object) list[str][source]#

Return the list of attributes which are found in class.

Parameters:

cls – Provided Python class related to operation.

Returns:

List of attributes which are found in class.

encommon.types.merge_dicts(dict1: dict[Any, Any], dict2: dict[Any, Any], force: bool | None = False, *, merge_list: bool = True, merge_dict: bool = True, paranoid: bool = False) dict[Any, Any][source]#

Recursively merge the contents of provided dictionaries.

Warning

This function will update the dict1 reference.

Example#

>>> dict1 = {'a': 'b', 'c': [1]}
>>> dict2 = {'a': 'B', 'c': [2]}
>>> merge_dicts(dict1, dict2)
{'a': 'b', 'c': [1, 2]}
>>> dict1
{'a': 'b', 'c': [1, 2]}
param dict1:

Primary dictionary which is merged into.

param dict2:

Secondary dictionary for primary updates.

param force:

Force overwriting concrete values in the primary dictionary with those from secondary. When None only overwrites if destination is None.

param merge_list:

Determines if merged or overwritten.

param merge_dict:

Determines if merged or overwritten.

param paranoid:

Perform an initial deepcopy on both of the provided dictionaries before performing merges.

returns:

Provided dictionary with the other merged in.

encommon.types.process(source: ProcessSource, *, recurse: bool = True, paranoid: bool = False, dedup_values: bool = False, allow_values: list[Any] | str | None = None, block_values: list[Any] | str | None = None, allow_keys: list[Any] | str | None = None, block_keys: list[Any] | str | None = None, allow_types: list[Any] | tuple[Any, ...] | None = None, block_types: list[Any] | tuple[Any, ...] | None = None, match_method: Literal['rematch', 'fnmatch'] = 'rematch', prune_empty: bool = False, processor: Callable[[...], Any] | None = None) ProcessSource[source]#

Process the provided iterable source updating in place.

Warning

This function will update the source reference.

Note

Parameters like allow_values accept either list of exact values or a single pattern string; regular expression or fnmatch pattern, see match_method.

Example#

>>> source = {'a': {'b': '1'}}
>>> process(source, processor=lambda _, v: int(v))
{'a': {'b': 1}}
>>> source
{'a': {'b': 1}}
param source:

Supported object processed in operation.

param recurse:

Process the provided source recursively.

param paranoid:

Perform deepcopy of source value first.

encommon.types.prune(source: ProcessSource, *, recurse: bool = True, paranoid: bool = False) ProcessSource[source]#

Process the provided source value removing empty values.

Warning

This function will update the source reference.

Parameters:
  • source – Supported object processed in operation.

  • recurse – Process the provided source recursively.

  • paranoid – Perform deepcopy of source value first.

encommon.types.rplstr(source: str, match: str, value: Any) str[source]#

Return the source string with the match value replaced.

Example#

>>> rplstr('foo', 'foo', 'bar')
'bar'
param source:

String that to be processed and returned.

param match:

What will be replaced within the string.

param value:

Replace value for the string is matched.

returns:

Source string with the match value replaced.

encommon.types.setate(source: dict[str, Any] | list[Any], path: str, value: Any, delim: str = '/') None[source]#

Define the value within the dictionary using notation.

Example#

>>> source = {'foo': {'bar': 'baz'}}
>>> source['foo']['bar']
'baz'
>>> setate(source, 'foo/bar', 'bop')
>>> source['foo']['bar']
'bop'
param source:

Dictionary object processed in notation.

param path:

Path to the value within the source object.

param value:

Value which will be defined at noted point.

param delim:

Override default delimiter between parts.

encommon.types.sort_dict(value: dict[Any, Any], reverse: bool = False) dict[Any, Any][source]#

Sort the keys within the dictionary and return new one.

Example#

>>> foo = {'b': 'be', 'a': 'ey'}
>>> sort_dict(foo)
{'a': 'ey', 'b': 'be'}
>>> sort_dict(foo, True)
{'b': 'be', 'a': 'ey'}
param value:

Dictionary whose keys are sorted into new.

param reverse:

Optionally reverse the sort direction.

returns:

New dictionary with keys sorted alphabetical.

encommon.types.strplwr(value: Any) str[source]#

Return the provided string but stripped and lower cased.

Example#

>>> strplwr('  Foo ')
'foo'
param value:

String which will be stripped and lowered.

returns:

Provided string but stripped and lower cased.

General Utilities#

encommon.utils.append_text(path: str | Path, content: str) None[source]#

Append the provided text content into provided file path.

Example#

>>> path.exists()
False
>>> append_text(path, 'foo')
>>> append_text(path, 'foo')
>>> read_text(path)
'foofoo'
param path:

Complete or relative path to the text file.

param content:

Content that will be written to the file.

encommon.utils.array_ansi(source: list[Any] | tuple[Any, ...] | set[Any] | dict[Any, Any] | BaseModel | DataclassInstance, *, indent: int = 0, colors: ArrayColors = ArrayColors(label=37, key=97, colon=37, hyphen=37, bool=93, none=33, str=92, num=93, times=96, empty=36, other=91)) str[source]#

Print the ANSI colorized iterable to the standard output.

Note

This massive function should be refactored, possibly into a class with methods where there are functions.

Example#

>>> array_ansi({'foo': 'bar'})
"\x1b[0;97mfoo\x1b[0;37m:\x1b[0;0m...
param source:

Value in supported and iterable formats.

param indent:

How many levels for initial indentation.

param colors:

Determine colors used with different types.

returns:

ANSI colorized string using inline directives.

encommon.utils.fuzz_match(values: str | list[str], patterns: str | list[str]) bool[source]#

Determine whether or not values are included by patterns.

Example#

>>> rgxp_match('one', ['on[a-z]', 'two'])
True

Example#

>>> rgxp_match('uno', ['on[a-z]', 'two'])
False
param values:

Value or values to enumerate for matching.

param patterns:

Patterns which values can match any one.

returns:

Boolean indicating outcome from the operation.

encommon.utils.kvpair_ansi(key: str, value: Any) str[source]#

Process and colorize keys and values for standard output.

Example#

>>> kvpair_ansi('k', 'v')
'\x1b[0;90mk\x1b[0;37m="\x1b[0;0m...
param key:

String value to use for the key name portion.

param value:

String value to use for the value portion.

returns:

ANSI colorized string using inline directives.

encommon.utils.load_sample(path: str | ~pathlib.Path, content: ~typing.Any | None = None, update: bool = False, *, default: ~typing.Callable[[~typing.Any], str] = <class 'str'>, replace: REPLACE | None = None) str[source]#

Load the sample file and compare using provided content.

Example#

>>> content = {'one': 'two'}
>>> load_sample(sample, content)
'{\n  "one": "two"\n}'

Example#

>>> load_sample(sample)
'{\n  "one": "two"\n}'
param path:

Complete or relative path for sample file.

param update:

Determine whether the sample is updated.

param content:

Content that will be processed as JSON.

param default:

Callable used when stringifying values.

param replace:

Optional values to replace in the file.

returns:

Content after processing using JSON functions.

encommon.utils.make_ansi(string: str) str[source]#

Parse the string and replace directives with ANSI codes.

Example#

>>> make_ansi('<c91>ERROR<c0>')
'\x1b[0;91mERROR\x1b[0;0m'
param string:

String containing directives to replace.

returns:

Provided string with the directives replaced.

encommon.utils.prep_diff(string1: str, string2: str, *, paths: tuple[str, str] | None = None, ignore: list[str] | None = None, ordered: bool = False, colors: bool = True) tuple[str, ...][source]#

Compare the two strings between each other line by line.

Parameters:
  • string1 – String that is used with the comparison.

  • string2 – String that is used with the comparison.

  • paths – Optional paths related to the strings.

  • ignore – Lines are ignored by regular expression.

  • ordered – Determines whether the lines are sorted.

  • colors – Determine whether console ANSI coloring.

Returns:

Lines output from diff comparison operation.

encommon.utils.prep_sample(content: ~typing.Any, *, default: ~typing.Callable[[~typing.Any], str] = <class 'str'>, replace: REPLACE | None = None, indent: int | None = 2) str[source]#

Return the content after processing as the sample value.

Example#

>>> prep_sample(['one', 'two'])
'[\n  "one",\n  "two"\n]'

Example#

>>> from ..types import Empty
>>> prep_sample({'one': Empty})
'{\n  "one": "Empty"\n}'
param content:

Content that will be processed as JSON.

param default:

Callable used when stringifying values.

param replace:

Optional values to replace in the file.

returns:

Content after processing as the sample value.

encommon.utils.print_ansi(string: str = '', method: Literal['stdout', 'print'] = 'stdout', output: bool = True) str[source]#

Print the ANSI colorized string to the standard output.

Example#

>>> print_ansi('<c91>ERROR<c0>')
'\x1b[0;91mERROR\x1b[0;0m'
param string:

String processed using inline directives.

param method:

Which method for standard output is used.

param output:

Whether or not hte output should be print.

returns:

ANSI colorized string using inline directives.

encommon.utils.read_sample(sample: str, *, replace: REPLACE | None = None, prefix: bool = True) str[source]#

Return the content after processing as the sample value.

Parameters:
  • sample – Content that will be processed as sample.

  • replace – Optional values to replace in the file.

  • prefix – Determine whether or not prefix is added.

Returns:

Content after processing as the sample value.

encommon.utils.read_text(path: str | Path) str[source]#

Read the text content from within the provided file path.

Example#

>>> path.exists()
False
>>> save_text(path, 'foo')
'foo'
>>> read_text(path)
'foo'
param path:

Complete or relative path to the text file.

returns:

Text content that was read from the file path.

encommon.utils.rvrt_sample(sample: str, *, replace: REPLACE | None = None) str[source]#

Return the content after processing as the sample value.

Parameters:
  • sample – Content that will be processed as sample.

  • replace – Optional values to replace in the file.

Returns:

Content after processing as the sample value.

encommon.utils.resolve_path(path: str | Path, replace: REPLACE | None = None) Path[source]#

Resolve the provided path replacing the magic keywords.

Example#

>>> resolve_path('/foo/bar')
PosixPath('/foo/bar')
param path:

Complete or relative path for processing.

param replace:

Optional values to replace in the path.

returns:

New resolved filesystem path object instance.

encommon.utils.resolve_paths(paths: PATHABLE, replace: REPLACE | None = None) tuple[Path, ...][source]#

Resolve the provided paths replacing the magic keywords.

Note

This will remove duplicative paths from the returned.

Example#

>>> resolve_paths(['/foo/bar'])
(PosixPath('/foo/bar'),)
param paths:

Complete or relative paths for processing.

param replace:

Optional values to replace in the path.

returns:

New resolved filesystem path object instances.

encommon.utils.rgxp_match(values: str | list[str], patterns: str | list[str], complete: bool = False) bool[source]#

Determine whether or not values are included by patterns.

Example#

>>> rgxp_match('one', ['on*', 'two'])
True

Example#

>>> rgxp_match('uno', ['on*', 'two'])
False
param values:

Value or values to enumerate for matching.

param patterns:

Patterns which values can match any one.

param complete:

Whether or not whole string must match.

returns:

Boolean indicating outcome from the operation.

encommon.utils.save_text(path: str | Path, content: str) str[source]#

Save the provided text content to the provided file path.

Example#

>>> path.exists()
False
>>> save_text(path, 'foo')
'foo'
>>> read_text(path)
'foo'
param path:

Complete or relative path to the text file.

param content:

Content that will be written to the file.

returns:

Text content that was read from the file path.

encommon.utils.stats_path(path: str | Path, replace: REPLACE | None = None, ignore: list[str] | None = None) dict[str, stat_result][source]#

Collect stats object for the complete or relative path.

Example#

>>> replace = {str(path): '/'}
>>> stats = stats_path(path, replace)
>>> stats['/hello.txt'].st_size
12
param path:

Complete or relative path for enumeration.

param replace:

Optional values to replace in the path.

param ignore:

Paths matching these patterns are ignored.

returns:

Metadata for files recursively found in path.

encommon.utils.strip_ansi(string: str) str[source]#

Return the provided string with the ANSI codes removed.

Example#

>>> strip_ansi('\x1b[0;91mERROR\x1b[0;0m')
'ERROR'
param string:

String which contains ANSI codes to strip.

returns:

Provided string with the ANSI codes removed.

exception encommon.utils.Unexpected[source]#

Bases: Exception

Exception when an unknown code condition is encountered.

WebKit Content#

encommon.utils.append_text(path: str | Path, content: str) None[source]#

Append the provided text content into provided file path.

Example#

>>> path.exists()
False
>>> append_text(path, 'foo')
>>> append_text(path, 'foo')
>>> read_text(path)
'foofoo'
param path:

Complete or relative path to the text file.

param content:

Content that will be written to the file.

encommon.utils.array_ansi(source: list[Any] | tuple[Any, ...] | set[Any] | dict[Any, Any] | BaseModel | DataclassInstance, *, indent: int = 0, colors: ArrayColors = ArrayColors(label=37, key=97, colon=37, hyphen=37, bool=93, none=33, str=92, num=93, times=96, empty=36, other=91)) str[source]#

Print the ANSI colorized iterable to the standard output.

Note

This massive function should be refactored, possibly into a class with methods where there are functions.

Example#

>>> array_ansi({'foo': 'bar'})
"\x1b[0;97mfoo\x1b[0;37m:\x1b[0;0m...
param source:

Value in supported and iterable formats.

param indent:

How many levels for initial indentation.

param colors:

Determine colors used with different types.

returns:

ANSI colorized string using inline directives.

encommon.utils.fuzz_match(values: str | list[str], patterns: str | list[str]) bool[source]#

Determine whether or not values are included by patterns.

Example#

>>> rgxp_match('one', ['on[a-z]', 'two'])
True

Example#

>>> rgxp_match('uno', ['on[a-z]', 'two'])
False
param values:

Value or values to enumerate for matching.

param patterns:

Patterns which values can match any one.

returns:

Boolean indicating outcome from the operation.

encommon.utils.kvpair_ansi(key: str, value: Any) str[source]#

Process and colorize keys and values for standard output.

Example#

>>> kvpair_ansi('k', 'v')
'\x1b[0;90mk\x1b[0;37m="\x1b[0;0m...
param key:

String value to use for the key name portion.

param value:

String value to use for the value portion.

returns:

ANSI colorized string using inline directives.

encommon.utils.load_sample(path: str | ~pathlib.Path, content: ~typing.Any | None = None, update: bool = False, *, default: ~typing.Callable[[~typing.Any], str] = <class 'str'>, replace: REPLACE | None = None) str[source]#

Load the sample file and compare using provided content.

Example#

>>> content = {'one': 'two'}
>>> load_sample(sample, content)
'{\n  "one": "two"\n}'

Example#

>>> load_sample(sample)
'{\n  "one": "two"\n}'
param path:

Complete or relative path for sample file.

param update:

Determine whether the sample is updated.

param content:

Content that will be processed as JSON.

param default:

Callable used when stringifying values.

param replace:

Optional values to replace in the file.

returns:

Content after processing using JSON functions.

encommon.utils.make_ansi(string: str) str[source]#

Parse the string and replace directives with ANSI codes.

Example#

>>> make_ansi('<c91>ERROR<c0>')
'\x1b[0;91mERROR\x1b[0;0m'
param string:

String containing directives to replace.

returns:

Provided string with the directives replaced.

encommon.utils.prep_diff(string1: str, string2: str, *, paths: tuple[str, str] | None = None, ignore: list[str] | None = None, ordered: bool = False, colors: bool = True) tuple[str, ...][source]#

Compare the two strings between each other line by line.

Parameters:
  • string1 – String that is used with the comparison.

  • string2 – String that is used with the comparison.

  • paths – Optional paths related to the strings.

  • ignore – Lines are ignored by regular expression.

  • ordered – Determines whether the lines are sorted.

  • colors – Determine whether console ANSI coloring.

Returns:

Lines output from diff comparison operation.

encommon.utils.prep_sample(content: ~typing.Any, *, default: ~typing.Callable[[~typing.Any], str] = <class 'str'>, replace: REPLACE | None = None, indent: int | None = 2) str[source]#

Return the content after processing as the sample value.

Example#

>>> prep_sample(['one', 'two'])
'[\n  "one",\n  "two"\n]'

Example#

>>> from ..types import Empty
>>> prep_sample({'one': Empty})
'{\n  "one": "Empty"\n}'
param content:

Content that will be processed as JSON.

param default:

Callable used when stringifying values.

param replace:

Optional values to replace in the file.

returns:

Content after processing as the sample value.

encommon.utils.print_ansi(string: str = '', method: Literal['stdout', 'print'] = 'stdout', output: bool = True) str[source]#

Print the ANSI colorized string to the standard output.

Example#

>>> print_ansi('<c91>ERROR<c0>')
'\x1b[0;91mERROR\x1b[0;0m'
param string:

String processed using inline directives.

param method:

Which method for standard output is used.

param output:

Whether or not hte output should be print.

returns:

ANSI colorized string using inline directives.

encommon.utils.read_sample(sample: str, *, replace: REPLACE | None = None, prefix: bool = True) str[source]#

Return the content after processing as the sample value.

Parameters:
  • sample – Content that will be processed as sample.

  • replace – Optional values to replace in the file.

  • prefix – Determine whether or not prefix is added.

Returns:

Content after processing as the sample value.

encommon.utils.read_text(path: str | Path) str[source]#

Read the text content from within the provided file path.

Example#

>>> path.exists()
False
>>> save_text(path, 'foo')
'foo'
>>> read_text(path)
'foo'
param path:

Complete or relative path to the text file.

returns:

Text content that was read from the file path.

encommon.utils.rvrt_sample(sample: str, *, replace: REPLACE | None = None) str[source]#

Return the content after processing as the sample value.

Parameters:
  • sample – Content that will be processed as sample.

  • replace – Optional values to replace in the file.

Returns:

Content after processing as the sample value.

encommon.utils.resolve_path(path: str | Path, replace: REPLACE | None = None) Path[source]#

Resolve the provided path replacing the magic keywords.

Example#

>>> resolve_path('/foo/bar')
PosixPath('/foo/bar')
param path:

Complete or relative path for processing.

param replace:

Optional values to replace in the path.

returns:

New resolved filesystem path object instance.

encommon.utils.resolve_paths(paths: PATHABLE, replace: REPLACE | None = None) tuple[Path, ...][source]#

Resolve the provided paths replacing the magic keywords.

Note

This will remove duplicative paths from the returned.

Example#

>>> resolve_paths(['/foo/bar'])
(PosixPath('/foo/bar'),)
param paths:

Complete or relative paths for processing.

param replace:

Optional values to replace in the path.

returns:

New resolved filesystem path object instances.

encommon.utils.rgxp_match(values: str | list[str], patterns: str | list[str], complete: bool = False) bool[source]#

Determine whether or not values are included by patterns.

Example#

>>> rgxp_match('one', ['on*', 'two'])
True

Example#

>>> rgxp_match('uno', ['on*', 'two'])
False
param values:

Value or values to enumerate for matching.

param patterns:

Patterns which values can match any one.

param complete:

Whether or not whole string must match.

returns:

Boolean indicating outcome from the operation.

encommon.utils.save_text(path: str | Path, content: str) str[source]#

Save the provided text content to the provided file path.

Example#

>>> path.exists()
False
>>> save_text(path, 'foo')
'foo'
>>> read_text(path)
'foo'
param path:

Complete or relative path to the text file.

param content:

Content that will be written to the file.

returns:

Text content that was read from the file path.

encommon.utils.stats_path(path: str | Path, replace: REPLACE | None = None, ignore: list[str] | None = None) dict[str, stat_result][source]#

Collect stats object for the complete or relative path.

Example#

>>> replace = {str(path): '/'}
>>> stats = stats_path(path, replace)
>>> stats['/hello.txt'].st_size
12
param path:

Complete or relative path for enumeration.

param replace:

Optional values to replace in the path.

param ignore:

Paths matching these patterns are ignored.

returns:

Metadata for files recursively found in path.

encommon.utils.strip_ansi(string: str) str[source]#

Return the provided string with the ANSI codes removed.

Example#

>>> strip_ansi('\x1b[0;91mERROR\x1b[0;0m')
'ERROR'
param string:

String which contains ANSI codes to strip.

returns:

Provided string with the ANSI codes removed.

exception encommon.utils.Unexpected[source]#

Bases: Exception

Exception when an unknown code condition is encountered.

WebKit JavaScript#

colordiv(input, label)#

Construct element for displaying the specified color.

Returns:

Object – jQuery-like object for the element.

datagrid(fields, values)#

Construct the table with the header using the contents.

Returns:

Object – jQuery-like object for the element.

datestamp(value)#

Return the timestamp using provided format for instance.

Returns:

Object – jQuery-like object for the element.

duration(seconds)#

Convert the provided seconds in a human friendly format.

Returns:

Object – jQuery-like object for the element.

assert(condition)#

Assert the provided condition similar how using Python.

Returns:

Boolean – Boolean for the conditional outcome.

whenready(callback)#

Attach the callback to the window session ready state.

isnull(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isempty(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isbool(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isstr(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isnum(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isquery(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isnode(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isnodes(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

istime(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

islist(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isdict(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

istrue(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

isfalse(value)#

Return the boolean indicating the conditional outcome.

Returns:

Boolean – Boolean for the conditional outcome.

loads(value)#

Return the object value from the provided JSON string.

dumps(value, indent)#

Return the JSON string from the provided object value.

svgicon(image, dimension)#

Return the simple construct for SVG based icon images.

Returns:

Object – jQuery-like object for the element.

message(level, about)#

Generate the severity based toast like message element.

Returns:

Object – jQuery-like object for the element.

moderate(label, icon, small)#

Construct for containing a wide variety of value types.

Returns:

Object – jQuery-like object for the element.

numeric(value, unit)#

Construct for containing a wide variety of value types.

Returns:

Object – jQuery-like object for the element.

numeric_count(value)#

Construct for containing a wide variety of value types.

Returns:

Object – jQuery-like object for the element.

numeric_bytes(value)#

Construct for containing a wide variety of value types.

Returns:

Object – jQuery-like object for the element.

numeric_ftemp(value)#

Construct for containing a wide variety of value types.

Returns:

Object – jQuery-like object for the element.

numeric_cftemp(value)#

Construct for containing a wide variety of value types.

Returns:

Object – jQuery-like object for the element.

statate(status, label, small)#

Construct for containing the value status information.

Returns:

Object – jQuery-like object for the element.

tagues(values, brafter)#

Construct for containing the values that are tag like.

Returns:

Object – jQuery-like object for the element.