Enasis Network Common Library#
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, model: 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 model:
Override default config validation model.
- property basic: dict[str, Any]
Return the configuration source loaded from the objects.
- Returns:
Configuration source loaded from the objects.
- property cargs: dict[str, Any]
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property config: dict[str, Any]
Return the configuration dumped from the Pydantic model.
- Returns:
Configuration dumped from the Pydantic model.
- property crypts: Crypts
Initialize the encryption instance using the parameters.
- Returns:
Instance of the encryption instance created.
- property files: ConfigFiles
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property jinja2: Jinja2
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property logger: Logger
Initialize the Python logging library using parameters.
- Returns:
Instance of Python logging library created.
- property merge: dict[str, Any]
Return the configuration source loaded from the objects.
- Returns:
Configuration source loaded from the objects.
- property model: 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 paths: ConfigPaths
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- pydantic model encommon.config.ConfigParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "ConfigParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "paths": { "anyOf": [ { "items": { "type": "string" }, "minItems": 1, "type": "array" }, { "type": "null" } ], "default": null, "description": "Location of configuration files", "title": "Paths" } }, "additionalProperties": false }
- Config:
extra: str = forbid
- Fields:
Parameters Container#
- pydantic model encommon.config.Params[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "Params", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "enconfig": { "anyOf": [ { "$ref": "#/$defs/ConfigParams" }, { "type": "null" } ], "default": null, "description": "Parameters for Config instance" }, "enlogger": { "anyOf": [ { "$ref": "#/$defs/LoggerParams" }, { "type": "null" } ], "default": null, "description": "Parameters for Logger instance" }, "encrypts": { "anyOf": [ { "$ref": "#/$defs/CryptsParams" }, { "type": "null" } ], "default": null, "description": "Parameters for Crypts instance" } }, "$defs": { "ConfigParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "paths": { "anyOf": [ { "items": { "type": "string" }, "minItems": 1, "type": "array" }, { "type": "null" } ], "default": null, "description": "Location of configuration files", "title": "Paths" } }, "title": "ConfigParams", "type": "object" }, "CryptParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "phrase": { "description": "Passphrase for the operations", "minLength": 1, "title": "Phrase", "type": "string" } }, "required": [ "phrase" ], "title": "CryptParams", "type": "object" }, "CryptsParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "phrases": { "additionalProperties": { "$ref": "#/$defs/CryptParams" }, "description": "Passphrases for the operations", "minProperties": 0, "title": "Phrases", "type": "object" } }, "required": [ "phrases" ], "title": "CryptsParams", "type": "object" }, "LoggerParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "stdo_level": { "anyOf": [ { "enum": [ "critical", "debug", "error", "info", "warning" ], "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Minimum logging message level", "title": "Stdo Level" }, "file_level": { "anyOf": [ { "enum": [ "critical", "debug", "error", "info", "warning" ], "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Minimum logging message level", "title": "File Level" }, "file_path": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Enable output to the log file", "title": "File Path" } }, "title": "LoggerParams", "type": "object" } }, "additionalProperties": false }
- Config:
extra: str = forbid
- Fields:
- field enconfig: Annotated[ConfigParams | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Parameters for Config instance')] = None
Parameters for Config instance
- field encrypts: Annotated[CryptsParams | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Parameters for Crypts instance')] = None
Parameters for Crypts instance
- field enlogger: Annotated[LoggerParams | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Parameters for Logger instance')] = None
Parameters for Logger instance
Configuration Content#
- 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.
- 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.
- 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.
- 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.
Configuration Logger#
- 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 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.
- 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.
- property logger_file: Logger
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 params: LoggerParams
Return the Pydantic model containing the configuration.
- Returns:
Pydantic model containing the configuration.
- property started: bool
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- pydantic model encommon.config.LoggerParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "LoggerParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "stdo_level": { "anyOf": [ { "enum": [ "critical", "debug", "error", "info", "warning" ], "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Minimum logging message level", "title": "Stdo Level" }, "file_level": { "anyOf": [ { "enum": [ "critical", "debug", "error", "info", "warning" ], "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Minimum logging message level", "title": "File Level" }, "file_path": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Enable output to the log file", "title": "File Path" } }, "additionalProperties": false }
- Config:
extra: str = forbid
- Fields:
- field 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)])] = None
Minimum logging message level
- Constraints:
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 fields: dict[str, str]
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property file_output: str
Format keyword arguments for writing to filesystem path.
- Returns:
String representation for the filesystem path.
- 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 stdo_output: str
Format keyword arguments for writing to standard output.
- Returns:
String representation for the standard output.
- property time: Time
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
Configuration Utilities#
- 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, replace: REPLACE | None = None) 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.
replace – Optional values to replace in the path.
- Returns:
New resolved filesystem path object instances.
Encryption and 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.
- 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.
- 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.
- delete(unique: str) None [source]
Delete the phrase from the internal dictionary reference.
- Parameters:
unique – Unique identifier of mapping passphrase.
- 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.
- classmethod keygen() str [source]
Return new randomly generated Fernet key for passphrase.
- Returns:
Randomly generated Fernet key for passphrase.
- property params: CryptsParams
Return the Pydantic model containing the configuration.
- Returns:
Pydantic model containing the configuration.
- pydantic model encommon.crypts.CryptsParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "CryptsParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "phrases": { "additionalProperties": { "$ref": "#/$defs/CryptParams" }, "description": "Passphrases for the operations", "minProperties": 0, "title": "Phrases", "type": "object" } }, "$defs": { "CryptParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "phrase": { "description": "Passphrase for the operations", "minLength": 1, "title": "Phrase", "type": "string" } }, "required": [ "phrase" ], "title": "CryptParams", "type": "object" } }, "additionalProperties": false, "required": [ "phrases" ] }
- Config:
extra: str = forbid
- Fields:
- field phrases: Annotated[dict[str, CryptParams], FieldInfo(annotation=NoneType, required=True, description='Passphrases for the operations', metadata=[MinLen(min_length=0)])] [Required]
Passphrases for the operations
- Constraints:
min_length = 0
Hashing Algorithms#
- 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 apache: 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 string: 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.
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 hsl: tuple[int, int, int]
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 source: str
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
Jinja2 Templating#
- 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 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.
- 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.
- 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.
- 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.
Network Addresses#
- 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 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 broadcast: str | None
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 hwaddr: str
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property islinklocal: bool
Return the boolean indicating whether instance is state.
- property islocalhost: bool
Return the boolean indicating whether instance is state.
- property isprivate: bool
Return the boolean indicating whether instance is state.
- property ispublic: bool
Return the boolean indicating whether instance is state.
- property netmask: 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 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 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.
- 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.
Advanced Time Structures#
- 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 after: Time
Return new object containing time just after the time.
- Returns:
Object containing time just after the time.
- property before: Time
Return new object containing time just before the time.
- Returns:
Object containing time just before the time.
- property elapsed: float
Determine the time in seconds occurring since instance.
- Returns:
Time in seconds occurring since the instance.
- property epoch: float
Return the seconds since the Unix epoch for the instance.
- Returns:
Seconds since the Unix epoch for the instance.
- property human: str
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property mpoch: float
Return milliseconds since the Unix epoch for the instance.
- Returns:
Seconds since the Unix epoch for the 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.
- property simple: str
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property since: float
Determine the time in seconds occurring since instance.
- Returns:
Time in seconds occurring since the instance.
- property source: datetime
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property spoch: int
Return the seconds since the Unix epoch for the instance.
- Returns:
Seconds since the Unix epoch for the instance.
- 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.
- property subsec: str
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.
- 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 compact: str
Return the compact format determined by source duration.
- Returns:
Compact format determined by source duration.
- property groups: int
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property short: str
Return the compact format determined by source duration.
- Returns:
Compact format determined by source duration.
- property smart: bool
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property source: float
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 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.
- 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.
- 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.
- property remains: float
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 time: Time
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property timer: float
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- pydantic model encommon.times.TimerParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "TimerParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "timer": { "description": "Seconds used for the interval", "title": "Timer", "type": "number" }, "start": { "description": "Optional value of timer start", "minLength": 1, "title": "Start", "type": "string" } }, "additionalProperties": false, "required": [ "timer", "start" ] }
- Config:
extra: str = forbid
- Fields:
- 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 children: dict[str, Timer]
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- 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.
- 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.
- property group: str
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property params: TimersParams
Return the Pydantic model containing the configuration.
- Returns:
Pydantic model containing the configuration.
- 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.
- 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.
- 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.
- property store: str
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 store_table: Type[TimersTable]
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- pydantic model encommon.times.TimersParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "TimersParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "timers": { "additionalProperties": { "$ref": "#/$defs/TimerParams" }, "description": "Seconds used for the interval", "minProperties": 0, "title": "Timers", "type": "object" } }, "$defs": { "TimerParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "timer": { "description": "Seconds used for the interval", "title": "Timer", "type": "number" }, "start": { "description": "Optional value of timer start", "minLength": 1, "title": "Start", "type": "string" } }, "required": [ "timer", "start" ], "title": "TimerParams", "type": "object" } }, "additionalProperties": false, "required": [ "timers" ] }
- Config:
extra: str = forbid
- Fields:
- field timers: Annotated[dict[str, TimerParams], FieldInfo(annotation=NoneType, required=True, description='Seconds used for the interval', metadata=[MinLen(min_length=0)])] [Required]
Seconds used for the interval
- Constraints:
min_length = 0
- 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 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 latest: 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.
- 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.
- property soonest: Time
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.
- 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.
- property walked: bool
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- pydantic model encommon.times.WindowParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "WindowParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "window": { "anyOf": [ { "type": "string" }, { "additionalProperties": { "type": "integer" }, "type": "object" } ], "description": "Period for scheduling window", "minLength": 1, "title": "Window" }, "start": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Determine when scope begins", "title": "Start" }, "stop": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Determine when scope ends", "title": "Stop" }, "anchor": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Optional anchor of the window", "title": "Anchor" }, "delay": { "description": "Time period of schedule delay", "minimum": 0, "title": "Delay", "type": "number" } }, "additionalProperties": false, "required": [ "window", "delay" ] }
- Config:
extra: str = forbid
- Fields:
- field anchor: Annotated[str | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Optional anchor of the window', metadata=[MinLen(min_length=1)])] = None
Optional anchor of the window
- Constraints:
min_length = 1
- field delay: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Time period of schedule delay', metadata=[Ge(ge=0)])] [Required]
Time period of schedule delay
- Constraints:
ge = 0
- field start: Annotated[str | None, FieldInfo(annotation=NoneType, required=False, default=None, description='Determine when scope begins', metadata=[MinLen(min_length=1)])] = None
Determine when scope begins
- Constraints:
min_length = 1
- 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 children: dict[str, Window]
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- 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.
- 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.
- property group: str
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- property params: WindowsParams
Return the Pydantic model containing the configuration.
- Returns:
Pydantic model containing the configuration.
- 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.
- 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.
- 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.
- 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 store: str
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 store_table: Type[WindowsTable]
Return the value for the attribute from class instance.
- Returns:
Value for the attribute from class instance.
- pydantic model encommon.times.WindowsParams[source]
Bases:
BaseModel
Process and validate the core configuration parameters.
Show JSON schema
{ "title": "WindowsParams", "description": "Process and validate the core configuration parameters.", "type": "object", "properties": { "windows": { "additionalProperties": { "$ref": "#/$defs/WindowParams" }, "description": "Period for scheduling windows", "minProperties": 0, "title": "Windows", "type": "object" } }, "$defs": { "WindowParams": { "additionalProperties": false, "description": "Process and validate the core configuration parameters.", "properties": { "window": { "anyOf": [ { "type": "string" }, { "additionalProperties": { "type": "integer" }, "type": "object" } ], "description": "Period for scheduling window", "minLength": 1, "title": "Window" }, "start": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Determine when scope begins", "title": "Start" }, "stop": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Determine when scope ends", "title": "Stop" }, "anchor": { "anyOf": [ { "minLength": 1, "type": "string" }, { "type": "null" } ], "default": null, "description": "Optional anchor of the window", "title": "Anchor" }, "delay": { "description": "Time period of schedule delay", "minimum": 0, "title": "Delay", "type": "number" } }, "required": [ "window", "delay" ], "title": "WindowParams", "type": "object" } }, "additionalProperties": false, "required": [ "windows" ] }
- Config:
extra: str = forbid
- Fields:
- field windows: Annotated[dict[str, WindowParams], FieldInfo(annotation=NoneType, required=True, description='Period for scheduling windows', metadata=[MinLen(min_length=0)])] [Required]
Period for scheduling windows
- Constraints:
min_length = 0
Datetime and Helpers#
- 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
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.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.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.
Unique Python Types#
Python Type Utilities#
- 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 isNone
.- 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.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.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.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.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.
- 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.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.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.funcname() str [source]
Return the current function name where code is running.
- Returns:
Current function name where code is running.
- 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.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.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.
Python Notation Helpers#
- 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.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.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.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.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.
Colorized Standard Output#
- 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.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.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.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.
Test Sample Utilities#
- 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: dict[str, ~typing.Any] | 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.prep_sample(content: ~typing.Any, *, default: ~typing.Callable[[~typing.Any], str] = <class 'str'>, replace: dict[str, ~typing.Any] | 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.read_sample(sample: str, *, replace: dict[str, Any] | 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.rvrt_sample(sample: str, *, replace: dict[str, Any] | 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.
Matching Expressions#
- 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.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.
File System and Paths#
- 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.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.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.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.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.
WebKit Content#
- class encommon.webkit.Content[source]
Access common content used with application interfaces.
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.