Skip to content

Commit 2eb6422

Browse files
authored
fix(python): clear error message when trying to serialize function (#824)
A common error seems to be to try to pass a function as a parameter into a JSII call (have seen 3 occurrences of this in the last week). Previously, this call would fail when trying to assing the `__jsii_type__` property to the function object. Specifically catch this case to give a helpful error message. Fixes aws/aws-cdk#4064.
1 parent 246efd1 commit 2eb6422

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

packages/jsii-python-runtime/src/jsii/_kernel/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import datetime
22
import inspect
33
import itertools
4+
from types import FunctionType, MethodType, BuiltinFunctionType, LambdaType
45

56
from typing import Any, List, Optional, Type, Union
67

@@ -126,6 +127,11 @@ def _make_reference_for_native(kernel, d):
126127
return d
127128
elif isinstance(d, (int, type(None), str, float, bool, datetime.datetime)):
128129
return d
130+
elif isinstance(d, (FunctionType, MethodType, BuiltinFunctionType, LambdaType)):
131+
# Whether a given object is a function-like object.
132+
# We won't use iscallable() since objects may implement __call__()
133+
# but we still want to serialize them as normal.
134+
raise JSIIError("Cannot pass function as argument here (did you mean to call this function?): %r" % d)
129135
else:
130136
d.__jsii__type__ = "Object"
131137
kernel.create(Object, d)

packages/jsii-python-runtime/tests/test_python.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ def test_inheritance_maintained(self):
2323

2424
assert base_names == ['DerivedStruct', 'MyFirstStruct']
2525

26+
def test_descriptive_error_when_passing_function(self):
27+
obj = jsii_calc.Calculator()
28+
29+
with pytest.raises(JSIIError, match="Cannot pass function as argument here.*"):
30+
obj.add(self.test_descriptive_error_when_passing_function)
2631

2732

2833
def find_struct_bases(x):

0 commit comments

Comments
 (0)