Skip to content

Commit 07d13bd

Browse files
committed
Propagate conversion hints for predicates, too
And while we're at it, stabilize the Converter API. Rather than calling the predicate and converter functions directly, we now introduce stable supports and convert methods that always accept hints kwargs, regardless of whether the linked predicate and/or converter functions do.
1 parent 3a02f95 commit 07d13bd

1 file changed

Lines changed: 23 additions & 12 deletions

File tree

src/scyjava/_convert.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,26 +28,37 @@ class Priority:
2828
LAST = -1e300
2929

3030

31+
def _has_kwargs(f):
32+
return not isjava(f) and any(
33+
p.kind == inspect.Parameter.VAR_KEYWORD
34+
for p in inspect.signature(f).parameters.values()
35+
)
36+
37+
3138
class Converter(NamedTuple):
3239
predicate: Callable[[Any], bool]
3340
converter: Callable[[Any], Any]
3441
priority: float = Priority.NORMAL
3542

43+
def supports(self, obj: Any, **hints: dict) -> bool:
44+
return (
45+
self.predicate(obj, **hints)
46+
if _has_kwargs(self.predicate)
47+
else self.predicate(obj)
48+
)
49+
50+
def convert(self, obj: Any, **hints: dict) -> Any:
51+
return (
52+
self.converter(obj, **hints)
53+
if _has_kwargs(self.converter)
54+
else self.converter(obj)
55+
)
56+
3657

3758
def _convert(obj: Any, converters: List[Converter], **hints: dict) -> Any:
38-
suitable_converters = filter(lambda c: c.predicate(obj), converters)
59+
suitable_converters = [c for c in converters if c.supports(obj, **hints)]
3960
prioritized = max(suitable_converters, key=lambda c: c.priority)
40-
41-
# check if selected converter supports hints
42-
uses_hints = not isjava(prioritized.converter) and any(
43-
p.kind == inspect.Parameter.VAR_KEYWORD
44-
for p in inspect.signature(prioritized.converter).parameters.values()
45-
)
46-
return (
47-
prioritized.converter(obj, **hints)
48-
if uses_hints
49-
else prioritized.converter(obj)
50-
)
61+
return prioritized.convert(obj, **hints)
5162

5263

5364
# -- Python to Java --

0 commit comments

Comments
 (0)