-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathpython.R
1918 lines (1582 loc) · 50 KB
/
python.R
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' @export
print.python.builtin.object <- function(x, ...) {
writeLines(py_repr(x))
invisible(x)
}
#' @importFrom utils str
#' @export
str.python.builtin.object <- function(object, ...) {
if (!py_available() || py_is_null_xptr(object))
cat("<pointer: 0x0>\n")
else
cat(py_str(object), "\n", sep = "")
}
#' @export
str.python.builtin.module <- function(object, ...) {
if (py_is_module_proxy(object)) {
cat("Module(", get("module", envir = object), ")\n", sep = "")
} else {
cat(py_str(object), "\n", sep = "")
}
}
#' @export
as.character.python.builtin.object <- function(x, ...) {
py_str(x)
}
#' Convert Python bytes to an R character vector
#'
#' @inheritParams base::as.character
#'
#' @param encoding Encoding to use for conversion (defaults to utf-8)
#' @param errors Policy for handling conversion errors. Default is 'strict'
#' which raises an error. Other possible values are 'ignore' and 'replace'.
#'
#' @export
as.character.python.builtin.bytes <- function(x, encoding = "utf-8", errors = "strict", ...) {
x$decode(encoding = encoding, errors = errors)
}
.operators <- new.env(parent = emptyenv())
fetch_op <- function(nm, .op, nargs = 1L) {
ensure_python_initialized()
if (is.null(fn <- .operators[[nm]])) {
force(.op)
if (is.function(.op))
op <- .op
else
op <- function(...) py_call(.op, ...)
if (nargs == 1L) {
call_op_and_maybe_convert <- function(...)
py_maybe_convert(op(...), py_has_convert(..1))
} else if (nargs == 2L) {
# Ops group generics
call_op_and_maybe_convert <- function(...) {
result <- op(...)
# if either dispatch object has convert=FALSE, don't convert
convert <-
!((inherits(..1, "python.builtin.object") && isFALSE(py_has_convert(..1))) ||
(inherits(..2, "python.builtin.object") && isFALSE(py_has_convert(..2))))
py_maybe_convert(result, convert)
}
} else stop("invalid nargs value: ", nargs)
fn <- .operators[[nm]] <- call_op_and_maybe_convert
}
fn
}
#' @export
"==.python.builtin.object" <- function(e1, e2) {
op <- fetch_op("eq", py_eval("lambda e1, e2: e1 == e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
"!=.python.builtin.object" <- function(e1, e2) {
op <- fetch_op("ne", py_eval("lambda e1, e2: e1 != e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
"<.python.builtin.object" <- function(e1, e2) {
op <- fetch_op("lt", py_eval("lambda e1, e2: e1 < e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
">.python.builtin.object" <- function(e1, e2) {
op <- fetch_op("gt", py_eval("lambda e1, e2: e1 > e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
">=.python.builtin.object" <- function(e1, e2) {
op <- fetch_op("ge", py_eval("lambda e1, e2: e1 >= e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
"<=.python.builtin.object" <- function(e1, e2) {
op <- fetch_op("le", py_eval("lambda e1, e2: e1 <= e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
# This uses PyObject_RichCompareBool(), which expects only py bools.
# It will throw an exception on, e.g., with numpy arrays,
# even though numpy.ndarray defines an __eq__() method.
py_compare <- function(a, b, op) {
ensure_python_initialized()
py_validate_xptr(a)
if (!inherits(b, "python.builtin.object"))
b <- r_to_py(b)
py_validate_xptr(b)
py_compare_impl(a, b, op)
}
#' @export
`+.python.builtin.object` <- function(e1, e2) {
if (missing(e2)) {
op <- fetch_op("pos", py_eval("lambda e1: +e1", convert = FALSE))
return(op(e1))
}
op <- fetch_op("add", py_eval("lambda e1, e2: e1 + e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`-.python.builtin.object` <- function(e1, e2) {
if (missing(e2)) {
op <- fetch_op("neg", py_eval("lambda e1: -e1", convert = FALSE))
return(op(e1))
}
op <- fetch_op("sub", py_eval("lambda e1, e2: e1 - e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`*.python.builtin.object` <-function(e1, e2) {
op <- fetch_op("*", py_eval("lambda e1, e2: e1 * e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`/.python.builtin.object` <- function(e1, e2) {
op <- fetch_op("/", py_eval("lambda e1, e2: e1 / e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`%/%.python.builtin.object` <- function(e1, e2) {
op <- fetch_op("//", py_eval("lambda e1, e2: e1 // e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`%%.python.builtin.object` <- function(e1, e2) {
op <- fetch_op("%", py_eval("lambda e1, e2: e1 % e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`^.python.builtin.object` <- function(e1, e2) {
op <- fetch_op("pow", import_builtins(FALSE)$pow,
nargs = 2L)
op(e1, e2)
}
#' @export
`&.python.builtin.object` <- function(e1, e2) {
op <- fetch_op("&", py_eval("lambda e1, e2: e1 & e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`|.python.builtin.object` <- function(e1, e2) {
op <- fetch_op("|", py_eval("lambda e1, e2: e1 | e2", convert = FALSE),
nargs = 2L)
op(e1, e2)
}
#' @export
`!.python.builtin.object` <- function(e1) {
op <- fetch_op("~", py_eval("lambda e1: ~ e1", convert = FALSE))
op(e1)
}
#' @export
`%*%.python.builtin.object` <-function(x, y) {
op <- fetch_op("@", py_eval("lambda x, y: x @ y", convert = FALSE),
nargs = 2L)
op(x, y)
}
#' @export
summary.python.builtin.object <- function(object, ...) {
str(object)
}
#' @export
`$.python.builtin.module` <- function(x, name) {
# resolve module proxies
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
`$.python.builtin.object`(x, name)
}
py_has_convert <- function(x) {
# resolve wrapped environment
x <- as.environment(x)
# get convert flag
if (exists("convert", x, inherits = FALSE))
get("convert", x, inherits = FALSE)
else
TRUE
}
py_maybe_convert <- function(x, convert) {
# if this is already an R object, nothing to do
if (!inherits(x, "python.builtin.object"))
return(x)
# if it's neither convertable nor callable,
# nothing to do
convertable <- convert || py_is_callable(x)
if (!convertable)
return(x)
# perform conversion
# capture previous convert for attr
attrib_convert <- py_has_convert(x)
# temporarily change convert so we can call py_to_r and get S3 dispatch
envir <- as.environment(x)
assign("convert", convert, envir = envir)
on.exit(assign("convert", attrib_convert, envir = envir), add = TRUE)
# call py_to_r
py_to_r(x)
}
# helper function for accessing attributes or items from a
# Python object, after validating that we do indeed have
# a valid Python object reference
py_get_attr_or_item <- function(x, name, prefer_attr) {
# resolve module proxies
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
# skip if this is a NULL xptr
if (py_is_null_xptr(x) || !py_available())
return(NULL)
# special handling for embedded modules (which don't always show
# up as "attributes")
if (py_is_module(x) && !py_has_attr(x, name)) {
module <- py_get_submodule(x, name, py_has_convert(x))
if (!is.null(module))
return(module)
}
# re-cast numeric values as integers
if (is.numeric(name))
name <- as.integer(name)
# attributes must always be indexed by strings, so if
# we receive a non-string 'name', we call py_get_item
if (!is.character(name)) {
item <- py_get_item(x, name)
return(py_maybe_convert(item, py_has_convert(x)))
}
# get the attrib and convert as needed
object <- NULL
if (prefer_attr) {
object <- py_get_attr(x, name)
} else {
# if we have an attribute, attempt to get the item
# but allow for fallback to that attribute. note that
# the logic here is fairly convoluted but is necessary
# to maintain backwards compatibility with a number of
# CRAN packages (hopefully we can simplify this in the
# future)
if (py_has_attr(x, name)) {
# try to get item
if (py_has_attr(x, "__getitem__"))
object <- py_get_item(x, name, silent = TRUE)
# fallback to attribute
if (is.null(object))
object <- py_get_attr(x, name)
} else {
# we don't have an attribute; only attempt item
# access and allow normal error propagation
object <- py_get_item(x, name)
}
}
py_maybe_convert(object, py_has_convert(x))
}
#' @export
`$.python.builtin.object` <- function(x, name) {
py_get_attr_or_item(x, name, TRUE)
}
#' @export
`[.python.builtin.object` <- function(x, name) {
py_get_attr_or_item(x, name, FALSE)
}
#' @export
`[[.python.builtin.object` <- function(x, name) {
py_get_attr_or_item(x, name, FALSE)
}
# the as.environment generic enables pytyhon objects that manifest
# as R functions (e.g. for functions, classes, callables, etc.) to
# be automatically converted to enviroments during the construction
# of PyObjectRef. This makes them a seamless drop-in for standard
# python objects represented as environments
#' @export
as.environment.python.builtin.object <- function(x) {
if (is.function(x))
attr(x, "py_object")
else
x
}
#' @export
`$<-.python.builtin.object` <- function(x, name, value) {
if (!py_is_null_xptr(x) && py_available())
py_set_attr(x, name, value)
else
stop("Unable to assign value (object reference is NULL)")
x
}
#' @export
`[[<-.python.builtin.object` <- `$<-.python.builtin.object`
#' @export
.DollarNames.python.builtin.module <- function(x, pattern = "") {
# resolve module proxies (ignore errors since this is occurring during completion)
result <- tryCatch({
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
TRUE
}, error = clear_error_handler(FALSE))
if (!result)
return(character())
# delegate
.DollarNames.python.builtin.object(x, pattern)
}
#' @importFrom utils .DollarNames
#' @export
.DollarNames.python.builtin.object <- function(x, pattern = "") {
# skip if this is a NULL xptr
if (py_is_null_xptr(x) || !py_available())
return(character())
# check for dictionary
if (inherits(x, "python.builtin.dict")) {
names <- py_dict_get_keys_as_str(x)
names <- names[substr(names, 1, 1) != '_']
Encoding(names) <- "UTF-8"
types <- rep_len(0L, length(names))
} else {
# get the names and filter out internal attributes (_*)
names <- py_suppress_warnings(py_list_attributes(x))
names <- names[substr(names, 1, 1) != '_']
# replace function with `function`
names <- sub("^function$", "`function`", names)
names <- sort(names, decreasing = FALSE)
# get the types
types <- py_suppress_warnings(py_get_attr_types(x, names))
}
# if this is a module then add submodules
if (inherits(x, "python.builtin.module")) {
name <- py_get_name(x)
if (!is.null(name)) {
submodules <- sort(py_list_submodules(name), decreasing = FALSE)
Encoding(submodules) <- "UTF-8"
names <- c(names, submodules)
types <- c(types, rep_len(5L, length(submodules)))
}
}
idx <- grepl(pattern, names)
names <- names[idx]
types <- types[idx]
if (length(names) > 0) {
# set types
oidx <- order(names)
names <- names[oidx]
attr(names, "types") <- types[oidx]
# specify a help_handler
attr(names, "helpHandler") <- "reticulate:::help_handler"
}
# return
names
}
#' @export
names.python.builtin.object <- function(x) {
as.character(.DollarNames(x))
}
#' @export
names.python.builtin.module <- function(x) {
as.character(.DollarNames(x))
}
#' @export
as.array.numpy.ndarray <- function(x, ...) {
py_to_r(x)
}
#' @export
as.matrix.numpy.ndarray <- function(x, ...) {
py_to_r(x)
}
#' @export
as.vector.numpy.ndarray <- function(x, mode = "any") {
a <- as.array(x)
as.vector(a, mode = mode)
}
#' @export
as.double.numpy.ndarray <- function(x, ...) {
a <- as.array(x)
as.double(a)
}
#' @importFrom graphics plot
#' @export
plot.numpy.ndarray <- function(x, y, ...) {
plot(as.array(x))
}
#' Create Python dictionary
#'
#' Create a Python dictionary object, including a dictionary whose keys are
#' other Python objects rather than character vectors.
#'
#' @param ... Name/value pairs for dictionary (or a single named list to be
#' converted to a dictionary).
#' @param keys Keys to dictionary (can be Python objects)
#' @param values Values for dictionary
#' @param convert `TRUE` to automatically convert Python objects to their R
#' equivalent. If you pass `FALSE` you can do manual conversion using the
#' [py_to_r()] function.
#'
#' @return A Python dictionary
#'
#' @note The returned dictionary will not automatically convert its elements
#' from Python to R. You can do manual conversion with the [py_to_r()]
#' function or pass `convert = TRUE` to request automatic conversion.
#'
#' @export
dict <- function(..., convert = FALSE) {
ensure_python_initialized()
# get the args
values <- list(...)
# flag indicating whether we should scan the parent frame for python
# objects that should serve as the key (e.g. a Tensor)
scan_parent_frame <- TRUE
# if there is a single element and it's a list then use that
if (length(values) == 1 && is.null(names(values)) && is.list(values[[1]])) {
values <- values[[1]]
scan_parent_frame <- FALSE
}
# get names
names <- names(values)
# evaluate names in parent env to get keys
frame <- parent.frame()
keys <- lapply(names, function(name) {
# allow python objects to serve as keys
if (scan_parent_frame && exists(name, envir = frame, inherits = TRUE)) {
key <- get(name, envir = frame, inherits = TRUE)
if (inherits(key, "python.builtin.object"))
key
else
name
} else {
if (grepl("^[0-9]+$", name))
name <- as.integer(name)
else
name
}
})
# construct dict
py_dict_impl(keys, values, convert = convert)
}
#' @rdname dict
#' @export
py_dict <- function(keys, values, convert = FALSE) {
ensure_python_initialized()
py_dict_impl(keys, values, convert = convert)
}
#' Create Python tuple
#'
#' Create a Python tuple object
#'
#' @inheritParams dict
#' @param ... Values for tuple (or a single list to be converted to a tuple).
#'
#' @return A Python tuple
#' @note The returned tuple will not automatically convert its elements from
#' Python to R. You can do manual conversion with the [py_to_r()] function or
#' pass `convert = TRUE` to request automatic conversion.
#'
#' @export
tuple <- function(..., convert = FALSE) {
ensure_python_initialized()
# get the args
values <- list(...)
# if it's a single value then maybe do some special resolution
if (length(values) == 1) {
# alias value
value <- values[[1]]
# reflect tuples back
if (inherits(value, "python.builtin.tuple"))
return(value)
# if it's a list then use the list as the values
if (is.list(value))
values <- value
}
# construct tuple
py_tuple(values, convert = convert)
}
#' @export
length.python.builtin.tuple <- function(x) {
if (py_is_null_xptr(x) || !py_available())
0L
else
py_tuple_length(x)
}
#' Length of Python object
#'
#' Get the length of a Python object. This is equivalent to calling
#' the Python builtin `len()` function on the object.
#'
#' Not all Python objects have a defined length. For objects without a defined
#' length, calling `py_len()` will throw an error. If you'd like to instead
#' infer a default length in such cases, you can set the `default` argument
#' to e.g. `1L`, to treat Python objects without a `__len__` method as having
#' length one.
#'
#' @param x A Python object.
#'
#' @param default The default length value to return, in the case that
#' the associated Python object has no `__len__` method. When `NULL`
#' (the default), an error is emitted instead.
#'
#' @return The length of the object, as a numeric value.
#'
#' @export
py_len <- function(x, default = NULL) {
# return 0 if Python not yet available
if (py_is_null_xptr(x) || !py_available())
return(0L)
# delegate to C++
py_len_impl(x, default)
}
#' @export
length.python.builtin.list <- function(x) {
py_list_length(x)
}
#' @export
length.python.builtin.object <- function(x) {
# return 0 if Python not yet available
if (py_is_null_xptr(x) || !py_available())
return(0L)
# otherwise, try to invoke the object's __len__ method
n <- py_len_impl(x, NA_integer_)
if (is.na(n))
# if the object didn't have a __len__ method, or __len__ raised an
# Exception, try instead to invoke its __bool__ method
return(as.integer(py_bool_impl(x)))
n
}
#' Python Truthiness
#'
#' Equivalent to `bool(x)` in Python, or `not not x`.
#'
#' If the Python object defines a `__bool__` method, then that is invoked.
#' Otherwise, if the object defines a `__len__` method, then `TRUE` is
#' returned if the length is nonzero. If neither `__len__` nor `__bool__`
#' are defined, then the Python object is considered `TRUE`.
#'
#' @param x, A python object.
#'
#' @return An R scalar logical: `TRUE` or `FALSE`. If `x` is a
#' null pointer or Python is not initialized, `FALSE` is returned.
#' @export
py_bool <- function(x) {
if (py_is_null_xptr(x) || !py_available())
FALSE
else
py_bool_impl(x)
}
#' Convert to Python Unicode Object
#'
#' @param str Single element character vector to convert
#'
#' @details By default R character vectors are converted to Python strings.
#' In Python 3 these values are unicode objects however in Python 2
#' they are 8-bit string objects. This function enables you to
#' obtain a Python unicode object from an R character vector
#' when running under Python 2 (under Python 3 a standard Python
#' string object is returned).
#'
#' @export
py_unicode <- function(str) {
ensure_python_initialized()
if (is_python3()) {
r_to_py(str)
} else {
py <- import_builtins()
py_call(py_get_attr(py, "unicode"), str)
}
}
#' Evaluate an expression within a context.
#'
#' The \code{with} method for objects of type \code{python.builtin.object}
#' implements the context manager protocol used by the Python \code{with}
#' statement. The passed object must implement the
#' \href{https://docs.python.org/2/reference/datamodel.html#context-managers}{context
#' manager} (\code{__enter__} and \code{__exit__} methods.
#'
#' @param data Context to enter and exit
#' @param expr Expression to evaluate within the context
#' @param as Name of variable to assign context to for the duration of the
#' expression's evaluation (optional).
#' @param ... Unused
#'
#' @export
with.python.builtin.object <- function(data, expr, as = NULL, ...) {
ensure_python_initialized()
# enter the context
context <- data$`__enter__`()
# check for as and as_envir
if (!missing(as)) {
as <- deparse(substitute(as))
as <- gsub("\"", "", as)
} else {
as <- attr(data, "as")
}
envir <- attr(data, "as_envir")
if (is.null(envir))
envir <- parent.frame()
# assign the context if we have an as parameter
if (!is.null(as)) {
assign(as, context, envir = envir)
}
# evaluate the expression and exit the context
tryCatch(force(expr),
finally = {
data$`__exit__`(NULL, NULL, NULL)
}
)
}
#' Create local alias for objects in \code{with} statements.
#'
#' @param object Object to alias
#' @param name Alias name
#'
#' @name with-as-operator
#'
#' @keywords internal
#' @export
"%as%" <- function(object, name) {
as <- deparse(substitute(name))
as <- gsub("\"", "", as)
attr(object, "as") <- as
attr(object, "as_envir") <- parent.frame()
object
}
#' Traverse a Python iterator or generator
#'
#' @param x Python iterator or iterable
#' @param it Python iterator or generator
#' @param f Function to apply to each item. By default applies the
#' \code{identity} function which just reflects back the value of the item.
#' @param simplify Should the result be simplified to a vector if possible?
#' @param completed Sentinel value to return from `iter_next()` if the iteration
#' completes (defaults to `NULL` but can be any R value you specify).
#'
#' @return For `iterate()`, A list or vector containing the results of calling
#' \code{f} on each item in \code{x} (invisibly); For `iter_next()`, the next
#' value in the iteration (or the sentinel `completed` value if the iteration
#' is complete).
#'
#' @details Simplification is only attempted all elements are length 1 vectors
#' of type "character", "complex", "double", "integer", or "logical".
#'
#' @export
iterate <- function(it, f = base::identity, simplify = TRUE) {
ensure_python_initialized()
# resolve iterator
it <- as_iterator(it)
# perform iteration
result <- py_iterate(it, f)
# simplify if requested and appropriate
if (simplify) {
# attempt to simplify if all elements are length 1
lengths <- sapply(result, length)
unique_length <- unique(lengths)
if (length(unique_length) == 1 && unique_length == 1) {
# then only simplify if we have a common primitive type
classes <- sapply(result, class)
unique_class <- unique(classes)
if (length(unique_class) == 1 &&
unique_class %in% c("character", "complex", "double", "integer", "logical")) {
result <- unlist(result)
}
}
}
# return invisibly
invisible(result)
}
#' @rdname iterate
#' @export
iter_next <- function(it, completed = NULL) {
# TODO: would like to use PyIter_Check() but that is only implemented
# as a macro in Python 2.x and requires copying more headers
iterable <- py_has_attr(it, "__next__") || py_has_attr(it, "next")
if (!iterable)
stop("object is not iterable", call. = FALSE)
py_iter_next(it, completed)
}
#' @rdname iterate
#' @export
as_iterator <- function(x) {
if (inherits(x, "python.builtin.iterator"))
x
else if (py_has_attr(x, "__iter__"))
x$`__iter__`()
else
stop("iterator function called with non-iterator argument", call. = FALSE)
}
#' Call a Python callable object
#'
#' @param ... Arguments to function (named and/or unnamed)
#'
#' @return Return value of call as a Python object.
#'
#' @keywords internal
#'
#' @export
py_call <- function(x, ...) {
ensure_python_initialized()
dots <- split_named_unnamed(list(...))
py_call_impl(x, dots$unnamed, dots$named)
}
#' Check if a Python object has an attribute
#'
#' Check whether a Python object \code{x} has an attribute
#' \code{name}.
#'
#' @param x A python object.
#' @param name The attribute to be accessed.
#'
#' @return \code{TRUE} if the object has the attribute \code{name}, and
#' \code{FALSE} otherwise.
#' @export
py_has_attr <- function(x, name) {
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
py_has_attr_impl(x, name)
}
#' Get an attribute of a Python object
#'
#' @param x Python object
#' @param name Attribute name
#' @param silent \code{TRUE} to return \code{NULL} if the attribute
#' doesn't exist (default is \code{FALSE} which will raise an error)
#'
#' @return Attribute of Python object
#' @export
py_get_attr <- function(x, name, silent = FALSE) {
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
py_get_attr_impl(x, name, silent)
}
#' Set an attribute of a Python object
#'
#' @param x Python object
#' @param name Attribute name
#' @param value Attribute value
#'
#' @export
py_set_attr <- function(x, name, value) {
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
py_set_attr_impl(x, name, value)
}
#' The Python None object
#'
#' Get a reference to the Python `None` object.
#'
#' @export
py_none <- function() {
ensure_python_initialized()
py_none_impl()
}
#' Delete an attribute of a Python object
#'
#' @param x A Python object.
#' @param name The attribute name.
#'
#' @export
py_del_attr <- function(x, name) {
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
py_del_attr_impl(x, name)
}
#' List all attributes of a Python object
#'
#'
#' @param x Python object
#'
#' @return Character vector of attributes
#' @export
py_list_attributes <- function(x) {
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
attrs <- py_list_attributes_impl(x)
Encoding(attrs) <- "UTF-8"
attrs
}
py_get_attr_types <- function(x,
names,
resolve_properties = FALSE)
{
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
py_get_attr_types_impl(x, names, resolve_properties)
}
#' Get an item from a Python object
#'
#' Retrieve an item from a Python object, similar to how
#' \code{x[name]} might be used in Python code to access an
#' item indexed by `key` on an object `x`. The object's
#' `__getitem__` method will be called.
#'
#' @param x A Python object.
#' @param key The key used for item lookup.
#' @param silent Boolean; when \code{TRUE}, attempts to access
#' missing items will return \code{NULL} rather than
#' throw an error.
#'
#' @family item-related APIs
#' @export
py_get_item <- function(x, key, silent = FALSE) {
ensure_python_initialized()
if (py_is_module_proxy(x))
py_resolve_module_proxy(x)
# NOTE: for backwards compatibility, we make sure to return an R NULL on error
if (silent) {
tryCatch(py_get_item_impl(x, key, FALSE), error = function(e) NULL)
} else {