Skip to content

Commit 6debf31

Browse files
committed
Fix: single-expression init functions in %py_class%
1 parent 93a515c commit 6debf31

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@
3535

3636
- Fixed issue where `create_layer_wrapper()` would not include arguments
3737
with a `NULL` default value in the returned wrapper.
38+
39+
- Fixed issue in `r_to_py.R6ClassGenerator` (and `%py_class%`) where
40+
single-expression `initialize` functions defined without `{` would error.
3841

3942
- Deprecated functions are no longer included in the package documentation index.
4043

R/py-classes.R

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,12 @@ as_py_method <- function(fn, name, env, convert) {
170170
}
171171

172172
# __init__ must return NULL
173-
if (name == "__init__")
174-
body(fn)[[length(body(fn)) + 1L]] <- quote(invisible(NULL))
173+
if (name == "__init__") {
174+
body(fn) <- substitute({
175+
body
176+
invisible(NULL)
177+
}, list(body = body(fn)))
178+
}
175179

176180
# python tensorflow does quite a bit of introspection on user-supplied
177181
# functions e.g., as part of determining which of the optional arguments

tests/testthat/test-py-class.R

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,17 @@ test_that("%py_class% can be lazy about initing python", {
8484

8585
expect_equal(res, 42)
8686
})
87+
88+
89+
test_that("%py_class% initialize", {
90+
# check that single expression init functions defined with `{` work
91+
92+
NaiveSequential %py_class% {
93+
initialize <- function(layers)
94+
self$layers <- layers
95+
}
96+
97+
x <- NaiveSequential(list(1, "2", 3))
98+
expect_identical(x$layers, list(1, "2", 3))
99+
100+
})

0 commit comments

Comments
 (0)