Skip to content

Commit 967f285

Browse files
committed
add shorthand for typing.Literal
1 parent 9b4ded8 commit 967f285

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/class_resolver/base.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""A base resolver."""
44

55
import logging
6+
import typing
67
from abc import ABC, abstractmethod
78
from typing import (
89
TYPE_CHECKING,
@@ -11,12 +12,14 @@
1112
Generic,
1213
Iterable,
1314
Iterator,
15+
Literal,
1416
Mapping,
1517
Optional,
1618
Set,
1719
)
1820

1921
from pkg_resources import iter_entry_points
22+
from typing_extensions import Self
2023

2124
from .utils import Hint, OptionalKwargs, X, Y, make_callback, normalize_string
2225

@@ -337,7 +340,7 @@ def extract_name(self, element: X) -> str: # noqa: D102
337340

338341
# docstr-coverage: inherited
339342
def lookup(self, query: Hint[X], default: Optional[X] = None) -> X: # noqa: D102
340-
str_query = str(query)
343+
str_query = self.normalize(str(query))
341344
if str_query in self.lookup_dict:
342345
return self.lookup_dict[str_query]
343346
if query is not None:
@@ -355,3 +358,18 @@ def make(self, query, pos_kwargs: OptionalKwargs = None, **kwargs) -> X: # noqa
355358
if pos_kwargs is not None:
356359
raise ValueError(f"{self.__class__.__name__} does not support positional arguments.")
357360
return self.lookup(query=query, **kwargs)
361+
362+
@classmethod
363+
def from_literal(cls, literal: Literal, **kwargs) -> Self:
364+
"""
365+
Construct a simple resolver for the given `typing.Literal`.
366+
367+
:param literal:
368+
the type annotation for literals.
369+
:param kwargs:
370+
additional keyword-based parameters passed to :meth:`__init__`
371+
372+
:return:
373+
a simple resolver for the literal values.
374+
"""
375+
return cls(elements=typing.get_args(literal), **kwargs)

0 commit comments

Comments
 (0)