Skip to content

Commit

Permalink
fix(python): clear error message when trying to serialize function (#824
Browse files Browse the repository at this point in the history
)

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.
  • Loading branch information
rix0rrr committed Sep 27, 2019
1 parent 246efd1 commit 2eb6422
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/jsii-python-runtime/src/jsii/_kernel/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import datetime
import inspect
import itertools
from types import FunctionType, MethodType, BuiltinFunctionType, LambdaType

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

Expand Down Expand Up @@ -126,6 +127,11 @@ def _make_reference_for_native(kernel, d):
return d
elif isinstance(d, (int, type(None), str, float, bool, datetime.datetime)):
return d
elif isinstance(d, (FunctionType, MethodType, BuiltinFunctionType, LambdaType)):
# Whether a given object is a function-like object.
# We won't use iscallable() since objects may implement __call__()
# but we still want to serialize them as normal.
raise JSIIError("Cannot pass function as argument here (did you mean to call this function?): %r" % d)
else:
d.__jsii__type__ = "Object"
kernel.create(Object, d)
Expand Down
5 changes: 5 additions & 0 deletions packages/jsii-python-runtime/tests/test_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ def test_inheritance_maintained(self):

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

def test_descriptive_error_when_passing_function(self):
obj = jsii_calc.Calculator()

with pytest.raises(JSIIError, match="Cannot pass function as argument here.*"):
obj.add(self.test_descriptive_error_when_passing_function)


def find_struct_bases(x):
Expand Down

0 comments on commit 2eb6422

Please sign in to comment.