File: test-python-dict.R

package info (click to toggle)
r-cran-reticulate 1.41.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,088 kB
  • sloc: cpp: 5,154; python: 620; sh: 13; makefile: 2
file content (160 lines) | stat: -rw-r--r-- 4,334 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
context("dict")

test_that("Python dictionaries can be created", {
  skip_if_no_python()
  expect_is(dict(), "python.builtin.dict")
})

test_that("Python dictionaries can be created with py_dict", {
  skip_if_no_python()
  expect_is(py_dict(list("a", "b", "c"), list(1,2,3)), "python.builtin.dict")
})

test_that("Python dictionaries can use python objects as keys", {
  skip_if_no_python()
  py <- import_builtins(convert = FALSE)
  key <- py$int(42)
  expect_error(dict(key = "foo"), NA)
  expect_is(py_dict(list(key), list("foo")), "python.builtin.dict")
})

test_that("Python dictionaries have numeric keys", {
  skip_if_no_python()
  expect_error(dict(`42` = "foo"), NA)
})

test_that("Python dictionaries can include numbers in their keys", {
  skip_if_no_python()
  expect_error(dict(foo42 = "foo"), NA)
})

test_that("Dictionary items can be get / set / removed with py_item APIs", {
  skip_if_no_python()

  d <- dict()
  one <- r_to_py(1)

  py_set_item(d, "apple", one)
  expect_equal(py_id(py_get_item(d, "apple")), py_id(one))

  py_del_item(d, "apple")
  expect_error(py_get_item(d, "apple"))
  expect_identical(py_get_item(d, "apple", silent = TRUE), NULL)
})

test_that("$, [ operators behave as expected", {
  skip_if_no_python()

  d <- dict(items = 1, apple = 42)

  expect_true(is.function(d$items))
  expect_true(py_bool(d['items'] == 1))

  expect_true(py_bool(d$apple == 42))
  expect_true(py_bool(d['apple'] == 42))

})

test_that("ordered dictionaries with non-string keys can be converted", {
  skip_if_no_python()

  builtins <- import_builtins(convert = FALSE)
  collections <- import("collections", convert = FALSE)

  t <- builtins$tuple(list(42))
  od <- collections$OrderedDict(list())
  od[[t]] <- 42

  result <- py_to_r(od)
  expect_identical(result, list("(42.0,)" = 42))

})

test_that("ordered dictionaries can be converted", {
  skip_if_no_python()

  collections <- import("collections", convert = FALSE)
  od <- collections$OrderedDict(list(tuple("a", 1),
                                     tuple("b", 2),
                                     tuple("c", 3)))

  result <- py_eval("lambda x: x")(od) # implicit conversion to R
  expect_identical(result, list(a = 1, b = 2, c = 3))

  result <- py_eval("lambda x: x", convert = FALSE)(od) # no conversion
  expect_identical(py_id(result), py_id(od))

})

test_that("py_to_r(dict) converts recursively, #1221", {
  skip_if_no_python()
  skip_if_no_numpy()
  skip_if_no_pandas()

  py <- py_run_string('
import numpy as np
import pandas as pd

np.random.seed(6012022)
tools = ["sas", "stata", "spss", "python", "r", "julia"]

random_df = pd.DataFrame({
"tool": np.random.choice(tools, 500),
"int": np.random.randint(1, 15, 500),
"num": np.random.randn(500),
"bool": np.random.choice([True, False], 500),
"date": np.random.choice(pd.date_range("2020-01-01", "2022-06-01"), 500)
})

# LIST OF DATA FRAMES
df_list = [df for i, df in random_df.groupby(["tool"])]

# DICT OF DATA FRAMES
# begining in Pandas 2.0, .groupby() returns the key as tuple(str,), previously, as a str.
df_dict = {i[0] if isinstance(i, tuple) else i: df for i, df in random_df.groupby(["tool"])}
', local = TRUE)

  rdf_list <- py$df_list
  lapply(rdf_list, expect_s3_class, "data.frame")

  rdf_dict <- py$df_dict
  lapply(rdf_list, expect_s3_class, "data.frame")

  for (i in seq_along(rdf_dict)) {
    attr(rdf_dict[[i]], "pandas.index") <- NULL
    attr(rdf_list[[i]], "pandas.index") <- NULL
  }

  expect_identical(rdf_list, unname(rdf_dict))
  expect_identical(sort(names(rdf_dict)),
                   sort(c("sas", "stata", "spss", "python", "r", "julia")))

})



test_that("py_to_r(list) converts recursively", {
  skip_if_no_python()

  expect_identical(py_eval("[1, [2, [3, 4]]]"),
                   list(1L, list(2L, c(3L, 4L))))

  str <- "[1, {'b': 3, 'c': ['d', 4]}, [3, 5]]"
  exp <- list(1L, list(b = 3L, c = list("d", 4L)), c(3L, 5L))

  expect_identical(py_eval(str), exp)

  x <- py_eval(str, convert = FALSE)
  expect_true(is_py_object(x))
  expect_s3_class(x, "python.builtin.list")
  expect_s3_class(x, "python.builtin.object")
  expect_identical(py_to_r(x), exp)

  x1 <- x[1]
  expect_true(is_py_object(x1))
  expect_s3_class(x1, "python.builtin.dict")
  expect_s3_class(x1, "python.builtin.object")
  expect_identical(py_to_r(x1), exp[[2]])


})