ClassResolver

class ClassResolver(classes: Collection[type[X]] | None = None, *, base: type[X], default: type[X] | None = None, suffix: str | None = None, synonyms: Mapping[str, type[X]] | None = None, synonym_attribute: str | list[str] | None = 'synonyms', base_as_suffix: bool = True, location: str | None = None)[source]

Bases: Generic[X], BaseResolver[type[X], X]

Resolve from a list of classes.

Initialize the resolver.

Parameters:
  • classes – A list of classes

  • base – The base class

  • default – The default class

  • suffix – The optional shared suffix of all instances. If not none, will override base_as_suffix.

  • synonyms – The optional synonym dictionary

  • synonym_attribute – The attribute or list of attributes to look in each class for synonyms. Defaults to synonyms. Explicitly set to None to turn off synonym lookup.

  • base_as_suffix – Should the base class’s name be used as the suffix if none is given? Defaults to true.

  • location – The location used to document the resolver in sphinx

Attributes Summary

options

Return the normalized option names.

synonym_attribute

Get the synonnym attribute for the class used for synonym lookup.

Methods Summary

docdata(query, *path[, default])

Lookup an element and get its docdata.

extract_name(element)

Get the name for an element.

extract_synonyms(element)

Get synonyms from an element.

from_entrypoint(group, **kwargs)

Make a resolver from the elements registered at the given entrypoint.

from_subclasses(base, *[, skip, ...])

Make a resolver from the subclasses of a given class.

get_option(*flags[, as_string, default, ...])

Get a click option for this resolver.

lookup(query[, default])

Lookup a class.

make(query[, pos_kwargs])

Instantiate a class with optional kwargs.

make_from_kwargs(data, key, *[, kwargs_suffix])

Instantiate a class, by looking up query/pos_kwargs from a dictionary.

make_many([queries, kwargs])

Resolve and compose several queries together.

make_safe(query[, pos_kwargs])

Run make, but pass through a none query.

make_table([key_fmt, cls_fmt, header, table_fmt])

Render the table of options in a format suitable for Sphinx documentation.

normalize(s)

Normalize the string with this resolve's suffix.

normalize_cls(cls)

Normalize the class name.

normalize_inst(x)

Normalize the class name of the instance.

optuna_lookup(trial, name)

Suggest an element from this resolver for hyper-parameter optimization in Optuna.

register(element[, synonyms, raise_on_conflict])

Register an additional element with this resolver.

register_entrypoint(group)

Register additional entries from an entrypoint.

signature(query)

Get the signature for the given class via inspect.signature().

supports_argument(query, parameter_name)

Determine if the class constructor supports the given argument.

Attributes Documentation

options

Return the normalized option names.

synonym_attribute

Get the synonnym attribute for the class used for synonym lookup.

Methods Documentation

docdata(query: str | X | None, *path: str, default: X | None = None) Any

Lookup an element and get its docdata.

Parameters:
  • query – The hint for looking something up in the resolver passed to lookup()

  • path – An optional path for traversing the resulting docdata dictionary

  • default – The default value to pass to lookup()

Returns:

The optional docdata retrieved with docdata.get_docdata()

extract_name(element: type[X]) str[source]

Get the name for an element.

extract_synonyms(element: type[X]) Collection[str][source]

Get synonyms from an element.

classmethod from_entrypoint(group: str, **kwargs: Any) Self

Make a resolver from the elements registered at the given entrypoint.

classmethod from_subclasses(base: type[X], *, skip: Collection[type[X]] | None = None, exclude_private: bool = True, exclude_external: bool = True, **kwargs: Any) ClassResolver[X][source]

Make a resolver from the subclasses of a given class.

Parameters:
  • base – The base class whose subclasses will be indexed

  • skip – Any subclasses to skip (usually good to hardcode intermediate base classes)

  • exclude_private – If true, will skip any class that comes from a module starting with an underscore (i.e., a private module). This is typically done when having shadow duplicate classes implemented in C

  • exclude_external – If true, will exclude any class that does not originate from the same package as the base class.

  • kwargs – remaining keyword arguments to pass to Resolver.__init__()

Returns:

A resolver instance

get_option(*flags: str, as_string: bool = False, default: Hint[X] = None, required: bool = False, prefix: str | None = None, delimiter: str | None = None, suffix: str | None = None, **kwargs: Any) Callable[[click.decorators.FC], click.decorators.FC]

Get a click option for this resolver.

Parameters:
  • flags – Positional arguments that are passed to click.option()

  • as_string – Should the value returned by processing be a string, or the instantiated element? Defaults to False, which returns the instantiated element

  • default – The default value for the option.

  • required – Is a value for this option required? If so, it’s good to give a default.

  • prefix – The string shown after the opening square bracket, before the list of possible values

  • suffix – The string shown before the closing square bracket, after the list of possible values

  • delimiter – The delimiter between values

  • kwargs – Keyword arguments forwarded to click.option().

Returns:

An instantiated option that can be used in click CLI

lookup(query: str | X | type[X] | None, default: type[X] | None = None) type[X][source]

Lookup a class.

make(query: str | X | type[X] | None, pos_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) X[source]

Instantiate a class with optional kwargs.

make_from_kwargs(data: Mapping[str, Any], key: str, *, kwargs_suffix: str = 'kwargs', **o_kwargs: Any) X[source]

Instantiate a class, by looking up query/pos_kwargs from a dictionary.

Parameters:
  • data – A dictionary that contains entry key and entry {key}_{kwargs_suffix}.

  • key – The key in the dictionary whose value will be put in the query argument of make().

  • kwargs_suffix – The suffix after key to look up the data. For example, if key='model' and kwargs_suffix='kwargs' (the default value), then the kwargs from make() are looked up via data['model_kwargs'].

  • o_kwargs – Additional kwargs to be passed to make()

Returns:

An instance of the X datatype parametrized by this resolver

make_many(queries: str | X | type[X] | None | Sequence[str | X | type[X] | None] = None, kwargs: Mapping[str, Any] | None | Sequence[Mapping[str, Any] | None] = None, **common_kwargs: Any) list[X][source]

Resolve and compose several queries together.

Parameters:
  • queries

    One of the following:

    1. none (will result in the default X),

    2. a single X, as either a class, instance, or string for class name

    3. a sequence of X’s, as either a class, instance, or string for class name

  • kwargs – Either none (will use all defaults), a single dictionary (will be used for all instances), or a list of dictionaries with the same length as queries

  • common_kwargs – additional keyword-based parameters passed to all instantiated instances.

Returns:

A list of X instances

Raises:

ValueError – If the number of queries and kwargs has a mismatch

make_safe(query: str | X | None, pos_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) Y | None

Run make, but pass through a none query.

make_table(key_fmt: str = '``{key}``', cls_fmt: str = ':class:`~{cls}`', header: tuple[str, str] = ('key', 'class'), table_fmt: str = 'rst', **kwargs: Any) str[source]

Render the table of options in a format suitable for Sphinx documentation.

Parameters:
  • key_fmt – A format string with a placeholder key which is filled with the normalized key for the class

  • cls_fmt – A format string with a place-holder cls which is filled by the fully qualified import name.

  • header – The header of the table.

  • table_fmt – The table format; passed to tabulate.tabulate().

  • kwargs – Additional keyword-based parameters passed to tabulate.tabulate().

Returns:

A string containing the formatted table.

normalize(s: str) str

Normalize the string with this resolve’s suffix.

normalize_cls(cls: type[X]) str[source]

Normalize the class name.

normalize_inst(x: X) str[source]

Normalize the class name of the instance.

optuna_lookup(trial: optuna.Trial, name: str) X

Suggest an element from this resolver for hyper-parameter optimization in Optuna.

Parameters:
  • trial – A trial object from optuna. Note that this object shouldn’t be constructed by the developer, and should only get constructed inside the optuna framework when using optuna.Study.optimize().

  • name – The name of the param within an optuna study.

Returns:

An element chosen by optuna, then run through lookup().

In the following example, Optuna is used to determine the best classification algorithm from scikit-learn when applied to the famous iris dataset.

import optuna
from sklearn import datasets
from sklearn.model_selection import train_test_split

from class_resolver.contrib.sklearn import classifier_resolver


def objective(trial: optuna.Trial) -> float:
    x, y = datasets.load_iris(return_X_y=True)
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.33, random_state=42,
    )
    clf_cls = classifier_resolver.optuna_lookup(trial, "model")
    clf = clf_cls()
    clf.fit(x_train, y_train)
    return clf.score(x_test, y_test)


study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100)
register(element: X, synonyms: Iterable[str] | None = None, raise_on_conflict: bool = True) None

Register an additional element with this resolver.

Parameters:
  • element – The element to register

  • synonyms – An optional iterable of synonyms to add for the element

  • raise_on_conflict – Determines the behavior when a conflict is encountered on either the normalized element name or a synonym. If true, will raise an exception. If false, will simply disregard the entry.

Raises:
register_entrypoint(group: str) None

Register additional entries from an entrypoint.

signature(query: str | X | type[X] | None) Signature[source]

Get the signature for the given class via inspect.signature().

supports_argument(query: str | X | type[X] | None, parameter_name: str) bool[source]

Determine if the class constructor supports the given argument.