rym-alias

The alias module provides name wranging functionality.

IMO, far too many software projects are fragile or backwards incompatible due to trivial name changes, such as “prod”, “PROD”, or “production”. These name variations may be due to different developers or different data sources – it shouldn’t matter.

We could setup some AI service with NLP, but that’s silly. We want things easier, not magic. We want to be explicit about the things we alias so that our users do not have to be.

Usage

Create an Alias

>>> from rym.alias import Alias
>>> x = Alias('prd', aliases=['prod', 'production'])
>>> x.identify('prod')
'prd'
>>> x.identify('PROD')
'prd'
>>> x.identity
'prd'
>>> x.all_names()
['PRD', 'PROD', 'PRODUCTION', 'prd', 'prod', 'production']

Specify Transformations

Upper and lower case transformations are performed by default, but additional transformations may be provided, too.

> Note: A lambda isn’t needed in this example as snakecase matches the > expected Callable[[str], str] signature already.

>>> from rym.alias import Alias
>>> import stringcase as sc
>>> x = Alias('fooBar', [], transforms=[lambda x: sc.snakecase(x)])
>>> x.identify('fooBar')
'fooBar'
>>> x.identify('foo_bar')
'fooBar'
>>> x.all_names()
['fooBar', 'foo_bar']

Use an AliasResolver to Manage Multiple Aliases

>>> from rym.alias import AliasResolver
>>> import stringcase as sc
>>> x = AliasResolver.build(
...   prd=['prod'],
...   dev=['develop'],
... ).add(
...   alp=['alpha'],
...   transforms=[sc.titlecase],
... )
>>> x.identify('PROD')
'prd'
>>> x.identify('develop')
'dev'
>>> x.identify('Alpha')
'alp'

You can specify transforms that apply to all aliases And if you need to provide an alias to a keyword, just use a dictionary.

>>> x.add({'transforms': 'etl'})
AliasResolver(aliases=[...])
>>> x.identify('etl')
'transforms'

API

class rym.alias.Alias(identity: ~typing.Hashable, aliases: ~typing.Iterable[~typing.Hashable], transforms: ~typing.Iterable[~typing.Callable[[~typing.Hashable], ~typing.Hashable]] = <factory>, strict: bool = False, logger: ~logging.Logger = None)

Simple name lookup.

  • Provides basic name lookup.

  • Support for enumerating common (or custom) variations, including

    upper and lower case or (de)essing.

identity

The “true name” of the alias.

Type:

Hashable

aliases

An iterable of names to alias.

Type:

Iterable[Hashable]

transforms

An iterable of functions to apply to each alias. Each function should take one string and return one string. Default: Upper and lower case of each alias.

Type:

Iterable[Callable[[Hashable], Hashable]]

add_alias(value: str) None

Add given alias to lookup, including transformed names.

add_transform(value: Callable[[str], str]) None

Add given transform and update alias lookup.

all_names(_sorted: Callable | None = None, **kwargs) Iterable[str]

Return all known aliases and transformations.

Parameters:
  • _sorted – Inject sorting function. Uses rym.alias.safesorted by default.

  • **kwargs – Keywords for “sorted”.

identify(value: str) str

Return identity for the given alias value.

Parameters:

value – Alias to match.

Returns:

Identity for the given alias.

Raises:

AliasError (KeyError) if unknown alias given.

set_transforms(value: Iterable[Callable[[str], str]]) None

Replace current transforms and update lookup.

Parameters:

value – Iterable of callables. None to clear current.

Returns:

None

class rym.alias.AliasResolver(aliases: Iterable[Alias], logger: Logger = None)

Group of aliases.

add(*args, strict: bool = True, transforms: Iterable[Callable[[str], str]] | None = '/home/runner/work/rym-py/rym-py/rym-alias/rym/alias/_aliasresolver.py', _resolver: Callable = None, **kwargs) AliasResolver

Add aliases to self.

classmethod build(*args, strict: bool = True, transforms: Iterable[Callable[[str], str]] | None = '/home/runner/work/rym-py/rym-py/rym-alias/rym/alias/_aliasresolver.py', logger: Logger = None, _resolver: Callable = None, **kwargs) AliasResolver

Build aliases to resolve.

Parameters:
  • *args – Supported formats as positional arguments

  • strict – If true, will raise if collisions detected.

  • transforms – Optional transforms to apply to all aliases. If given, will replace existing transforms on each alias. Use ‘None’ to disable all transformations

  • _resolver – Inject an alias factory.

  • **kwargs – Supported formats as keyword arguments

Returns:

An AliasResolver instance.

See also

alias_factory

classmethod find_collisions(*aliases: Iterable[Alias], logger: Logger = None) Iterable[str]

Check for alias collisions.

identify(value: str, default: Any = '/home/runner/work/rym-py/rym-py/rym-alias/rym/alias/_aliasresolver.py') str

Return identity for the given alias value.

Parameters:

value – Alias to match.

Returns:

Identity for the given alias.

Raises:

AliasError (KeyError) if unknown alias given.

class rym.alias.Coercer(explicit: ~typing.Callable = <function coerce_explicit>, implicit: ~typing.Callable = <function coerce_implicit>, logger: ~logging.Logger = None)

Data type converter.

coerce(value: Any, type_: str | Callable | None = '/home/runner/work/rym-py/rym-py/rym-alias/rym/alias/_coerce.py', **kwargs) Any

Coerce given value

Parameters:
  • value – Thing to coerce.

  • type – Optional coercion type if known

  • logger – Optional logger (easier for testing)

  • **kwargs – Passed to coercion functions

Returns:

_description_

Return type:

Any

See also

coerce_explicit coerce_implicit

explicit(value: Any, use_safe: bool = True, _resolve_type: Callable | None = None, **kwargs) Any

Coerce given value to given type.

Parameters:
  • type – Name, alias or callable

  • value – Thing to coerce

  • use_safe – If True, will perform safe coercions where possible.

  • **kwargs – Passed to converter

Returns:

Coerced value.

Raises:

implicit(alias: AliasResolver | None = None) Any

Naively detect type and convert.

Implicit conversion assumes you’ve provided a string. If not a string, we’ll try an alias lookup before returning as is.

Parameters:
  • value – The thing to convert.

  • alias – An AliasResolver

Returns:

The converted value.

Raises:

InvalidConversionError (ValueError) if unable to convert.

See also

converter_names(…)

exception rym.alias.CoercionError

Raise if unable to coerce given value to specific type.

class rym.alias.FrozenAlias(identity: Hashable, _lookup: Iterable[Hashable])

Hashable Alias.

all_names(_sorted: Callable | None = None, **kwargs) Iterable[str]

Return all known aliases and transformations.

Parameters:
  • _sorted – Inject sorting function. Uses rym.alias.safesorted by default.

  • **kwargs – Keywords for “sorted”.

exception rym.alias.InvalidConverterError

Raise if unsupported conversion requested.

rym.alias.coerce_explicit(type_: str | Callable, value: Any, use_safe: bool = True, _resolve_type: Callable | None = None, **kwargs) Any

Coerce given value to given type.

Parameters:
  • type – Name, alias or callable

  • value – Thing to coerce

  • use_safe – If True, will perform safe coercions where possible.

  • **kwargs – Passed to converter

Returns:

Coerced value.

Raises:

rym.alias.coerce_implicit(value: Any, alias: AliasResolver | None = None) Any

Naively detect type and convert.

Implicit conversion assumes you’ve provided a string. If not a string, we’ll try an alias lookup before returning as is.

Parameters:
  • value – The thing to convert.

  • alias – An AliasResolver

Returns:

The converted value.

Raises:

InvalidConversionError (ValueError) if unable to convert.

See also

converter_names(…)

rym.alias.get_default_coercer() Coercer

Return an instance of the default coercer.

rym.alias.resolve_aliases(*args, transforms: Iterable[Callable[[str], str]] | None = '/home/runner/work/rym-py/rym-py/rym-alias/rym/alias/_aliasresolver.py', **kwargs) Iterable[Alias]

Build aliases from multiple supported formats.

Supported Formats:
  • Alias instances

  • Alias keywords

    e.g., {‘identity’: ‘foo’, ‘aliases’: ‘bar’, ‘transform’: ‘upper’}

  • Alias mapping (does not support transform definition)

    e.g., {‘foo’: [‘bar’]}

  • None

  • Iterable of supported format

  • Encoding of supported format
    • May be string (json only)

    • May be file path (json, toml, yaml)

NOTE: TOML requires a root object (not an array)

Parameters:
  • *args – Supported formats as positional arguments

  • transforms – Optional transforms to apply to all aliases. Use ‘None’ to disable.

  • **kwargs – Supported formats as keyword arguments

Returns:

Iterable of Alias instances.

rym.alias.resolve_type(value: str | Callable, use_safe: bool = True, _resolver: AliasResolver | None = None, _safe_resolver: AliasResolver | None = None) Callable

Return callable for given value.

Parameters:

value – Alias or callable

Returns:

Callable NOTE: If given value is callable, it will be returned as is.

Raises:

InvalidConverterError if unknown converter requested.

rym.alias.resolve_variations(value: Any) Callable[[str], str]

Resolve given value into callables.

Supported:
  • string names (see rym.alias.variation)

  • callables (should take and return a single string)

  • iterables of either of the others

Parameters:

value – One of the supported input.

Returns:

An iterable of resolved variation callables.

Raises:

TypeError for invalid input.

rym.alias.safesorted(iterable: Iterable, *, key=None, **kwargs) Iterable

Return a new sorted list from items in iterable.