-
Notifications
You must be signed in to change notification settings - Fork 0
/
python.hh
1608 lines (1307 loc) · 45.6 KB
/
python.hh
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2019, Arthus Leroy <[email protected]>
* On https://github.com/arthus-leroy/Python
* All rights reserved. */
# pragma once
// WARNING: requires use of pkg-config (pkg-config --cflags --libs python3)
# include <Python.h>
# include <iostream>
# include <memory>
# include <cassert>
# include <filesystem>
# include <sstream>
# include <array>
# include <vector>
# include <list>
# include <map>
# include <regex>
# include <locale>
# include <codecvt>
# include "backtrace.hh"
// INCREF/DECREF is any Instance of the object
/// Enable logging of INCREF and DECREF
//# define PYDEBUG_INCREF
//# define PYDEBUG_DECREF
// Construction and Destruction are the creation and release of the Python object
// To be noted, the object can be destroyed, but still held by another object
/// Enable logging of construction and destruction
//# define PYDEBUG_CONST
//# define PYDEBUG_DEST
namespace
{
[[maybe_unused]] std::string get_typename(const char* s, int skips = 0)
{
char* start = const_cast<char*>(s);
char* end = const_cast<char*>(s);
for (; *start; start++)
if (*start == '=')
{
if (skips)
skips--;
else
break;
}
if (*start)
start++;
end = start;
while (*end && *end != ';')
end++;
return std::string(start, end);
}
# define GET_TYPENAME(I) get_typename(__PRETTY_FUNCTION__, I)
template <typename T>
auto is_iterable_type() -> decltype(
std::begin(std::declval<T&>()) != std::end(std::declval<T&>()), // operator!=
void(),
++std::declval<decltype(std::begin(std::declval<T&>()))&>(), // operator++
void(*std::begin(std::declval<T&>())), // operator*
std::true_type{});
template <typename T>
using is_iterable = decltype(is_iterable_type<T>());
std::string escape(const std::string str)
{
std::string ret(str);
for (std::size_t i = 0; i < ret.size(); i++)
switch (ret[i])
{
case '\a': ret.insert(i, "\\"); ret.replace(++i, 1, "a"); break;
case '\b': ret.insert(i, "\\"); ret.replace(++i, 1, "b"); break;
case '\f': ret.insert(i, "\\"); ret.replace(++i, 1, "f"); break;
case '\n': ret.insert(i, "\\"); ret.replace(++i, 1, "n"); break;
case '\r': ret.insert(i, "\\"); ret.replace(++i, 1, "r"); break;
case '\t': ret.insert(i, "\\"); ret.replace(++i, 1, "t"); break;
case '\v': ret.insert(i, "\\"); ret.replace(++i, 1, "v"); break;
}
return ret;
}
// disabled as it litteraly *doubles* the duration of the tests
// const auto kwargs_regex = std::regex("\"([^\"]*)\": ");
// convert from char_t -> char
template <typename char_t>
std::wstring_convert<std::codecvt_utf8<char_t>, char_t> converter;
}
/// Wrapper around PyObject* taking care of INCREF/DECREF and debug
struct PyRef
{
PyRef(PyObject* ptr, const std::string& name, const bool borrowed = false)
: ptr(ptr), name(escape(name))
{
if (ptr == nullptr)
return;
# ifdef PYDEBUG_CONST
std::cout << "Construction of " << this->name << std::endl;
# endif
// increase life duration to outlive it owner
if (borrowed)
Py_INCREF(ptr);
}
PyRef(void)
: ptr(nullptr), name("NULL")
{}
PyRef(const PyRef& o)
{
*this = o;
}
PyRef& operator=(const PyRef& o)
{
ptr = o.ptr;
name = o.name;
if (ptr == nullptr)
return *this;
Py_INCREF(ptr);
# ifdef PYDEBUG_INCREF
std::cout << "Incref of " << name << std::endl;
# endif
return *this;
}
operator PyObject*() const
{
return ptr;
}
// WARNING: bool is famous for creating overloading problems as it converts to int
operator bool() const
{
return ptr;
}
// NOTE: destruction won't work on borrowed reference with owner still alive
// (it will not be logged) like a module's dict or a container's item
~PyRef()
{
if (ptr == nullptr)
return;
# ifdef PYDEBUG_DECREF
std::cout << "Decref of " << name
<< " (" << (ptr->ob_refcnt - 1) << " instances remaining)" << std::endl;
# endif
# ifdef PYDEBUG_DEST
if (ptr->ob_refcnt == 1)
std::cout << "Destruction of " << name << std::endl;
# endif
Py_DECREF(ptr);
}
PyObject* ptr;
std::string name;
};
/// Wrapper around PyRef taking care of all the functions and the logic behind
class Python
{
public:
using utf32_t = std::basic_string<char32_t>;
using utf16_t = std::basic_string<char16_t>;
// using utf8_t = std::basic_string<char8_t>; // C++20
using utf8_t = std::basic_string<char>;
enum class Type
{
Object,
Dict,
Sequence, // list, array
};
/// Error class to indicate any normal error (look at the trace for more info)
class PythonError : std::exception
{ };
/// Error class to indicate the end of a "for ... in ..." iteration
class StopIteration : std::exception
{ };
// FIXME: refactor the whole class
/// Intermediary class to recongnize starred expressions
template <typename T>
class Starred
{
public:
Starred(T&& ref)
: ref_(ref)
{
static_assert(is_starred<0, Starred<T>>::value);
}
Starred(T& ref)
: ref_(ref)
{
static_assert(is_starred<0, Starred<T>>::value);
}
// For argument expansion (like tuple(1, 2, *args, 3))
operator Python()
{
Python ref = ref_;
assert(static_cast<PyObject*>(ref) != nullptr);
if (PySequence_Check(ref))
return ref;
else if (PyDict_Check(ref))
return ref_.keys();
else
throw std::invalid_argument("starred expression must be an iterable");
}
auto operator=(Python o)
{
return (ref_ = o);
}
private:
T& ref_;
};
private:
static void initialize()
{
if (initialized_ == false)
{
Py_Initialize();
initialized_ = true;
}
}
static void err(const char* func)
{
if (mute_error)
return;
if (PyErr_Occurred())
{
if (finally_func)
finally_func();
std::cerr << "\nIn function \"" << func << "\":" << std::endl;
PyErr_Print();
std::cerr << std::endl;
# ifdef BACKTRACE
// skip "err" trace
backtrace(1);
# endif
throw PythonError();
}
}
template <typename T>
static std::string to_string(const T t)
{
// char-likes
if constexpr(std::is_same<T, char>::value || std::is_same<T, wchar_t>::value
|| std::is_same<T, char16_t>::value || std::is_same<T, char32_t>::value)
return to_string(std::basic_string<T>(1, t));
// numbers
else
{
std::stringstream ss;
ss << t;
return ss.str();
}
}
// string-likes
static std::string to_string(const std::string& s)
{ return s; }
template <typename char_t>
static std::string to_string(const std::basic_string<char_t>& s)
{ return converter<char_t>.to_bytes(s); }
template <typename char_t>
static std::string to_string(const char_t* s)
{ return to_string(std::basic_string<char_t>(s)); }
// misc
static std::string to_string(const PyRef& s)
{ return s.name; }
static std::string to_string(Python& s)
{ return s.name(); }
static std::string to_string(std::nullptr_t)
{ return "NULL"; }
static std::string to_string(const std::filesystem::path& s)
{ return s.string(); }
/// Wrapper around PyRef, taking a key, used to access an element
template <typename key_t>
class PyIndexProxy
{
/// Force convertion to Python (parent class)
Python parent()
{
return *this;
}
public:
PyIndexProxy(const PyRef& object, const Type type, const key_t& key)
: object_(object), type_(type), key_(key)
{
// restrict types (until constraints in C++20)
static_assert(std::is_same<key_t, std::string>::value
|| std::is_same<key_t, char*>::value
|| std::is_convertible<key_t, PyObject*>::value
|| std::is_convertible<key_t, int>::value);
}
PyIndexProxy(const PyIndexProxy<key_t>& proxy)
: PyIndexProxy(proxy.object_, proxy.type_, proxy.key_)
{}
operator PyObject*()
{
assert(object_.ptr != nullptr);
PyObject* ret = nullptr;
switch (type_)
{
case Type::Object: ret = PyObject_GetAttr(object_, Python(key_)); break;
case Type::Dict:
case Type::Sequence:ret = PyObject_GetItem(object_, Python(key_)); break;
}
err("assign");
return ret;
}
// WARNING: as it's a lazy getter, you need to force convertion if you want to keep the object
/// Implicit convertion to Python
operator Python()
{
PyObject* ret = *this;
if (type_ == Type::Object)
return Python(ret, object_.name + "." + to_string(key_), true);
else if constexpr(std::is_same<key_t, Python>::value)
return Python(ret, object_.name + "[" + key_.name() + "]");
else if constexpr(std::is_convertible<key_t, std::string>::value)
return Python(ret, object_.name + "[\"" + to_string(key_) + "\"]", true);
else
return Python(ret, object_.name + "[" + to_string(key_) + "]", true);
}
auto& operator=(PyObject* object)
{
assert(object_.ptr != nullptr);
switch (type_)
{
case Type::Object: PyObject_SetAttr(object_, Python(key_), object); break;
case Type::Dict:
case Type::Sequence:PyObject_SetItem(object_, Python(key_), object); break;
}
err("assign");
return *this;
}
auto& operator=(Python object)
{
// explicit convertion to avoid looping on itself
return operator=(static_cast<PyObject*>(object));
}
// FIXME: ambiguous situations, risk of error
// auto proxy = PyIndexProxy() -> assignation
// proxy = PyIndexProxy() -> item setter
auto& operator=(PyIndexProxy<key_t> proxy)
{
// setter
if (object_)
operator=(static_cast<PyObject*>(proxy));
// assignation
else
{
object_ = proxy.object_;
type_ = proxy.type_;
key_ = proxy.key_;
}
return *this;
}
template <typename T>
auto& operator=(T t)
{
return operator=(Python(t));
}
auto name() const
{
return object_.name;
}
auto key() const
{
return key_;
}
// Since we can't overload "operator.()", we need to duck-type our proxy class
auto operator[](const std::string& key) { return parent()[key]; }
auto operator[](const Py_ssize_t key) { return parent()[key]; }
auto call(Python args = nullptr, Python kwargs = nullptr)
{ return parent().call(args, kwargs); }
auto string(void) { return parent().string(); }
auto is_valid(void) { return parent().is_valid(); }
auto print(void) { return parent().print(); }
auto operator()(Python args = nullptr, Python kwargs = nullptr)
{ return parent()(args, kwargs); }
private:
PyRef object_;
Type type_;
key_t key_;
};
template <typename key_t>
static std::string to_string(PyIndexProxy<key_t>& s) { return s.name() + "[" + to_string(s.key()) + "]"; }
// Use this with caution, it shouldn't be used in place of another constructor
// as you can't trace the source
// Don't use with any Py_* function returning a new reference (leaks)
Python(PyObject* o)
: ref_(o, "PyObject*", true)
{}
public:
// NOTE: operator[] won't let you access attribute of iterable, you must use attr
/// Access operators
# define ACCESS(TYPE) auto operator[](TYPE key) \
{ \
assert(is_valid()); \
return PyIndexProxy(ref_, get_type(), key); \
}
ACCESS(const std::string&)
ACCESS(const Py_ssize_t)
ACCESS(Python)
/// Release the ressources of the global Python instance
static void terminate(void)
{
Py_Finalize();
initialized_ = false;
}
/// Disable/Enable error raising
static void mute_errors(const bool value)
{
mute_error = value;
}
/// Import the module \var name
static Python import(const std::string& name)
{
initialize();
auto module = Python(PyImport_ImportModule(name.c_str()), name);
err("import");
auto dict = PyModule_GetDict(module);
err("import"); // a bit careful doesn't hurt, isn't it ?
return Python(dict, "module " + name, true);
}
private:
template <typename ...Args>
static auto dict_extractor(Python dict, const std::string& name, const Args&... args)
{
if constexpr(sizeof...(Args))
return std::tuple_cat(std::tuple(dict[name]), dict_extractor(dict, args...));
return std::tuple(dict[name]);
}
public:
/// Import object from the module \var name
template <typename ...Args>
static auto from_import(const std::string& name, const Args&... args)
{
return dict_extractor(import(name), args...);
}
/// Return the python builtins
static Python builtins(void)
{
initialize();
auto ptr = PyEval_GetBuiltins();
err("builtins");
return Python(ptr, "builtins", true);
}
/// Call a builtin function
static Python call_builtin(const std::string& name, Python args = nullptr, Python kwargs = nullptr)
{
auto main = builtins();
return main[name].call(args, kwargs);
}
/// Evaluate python code
static Python eval(const std::string& content, int type, Python globals, Python locals)
{
PyObject* ret;
globals["__builtins__"] = PyEval_GetBuiltins();
ret = PyRun_String(content.c_str(), type, globals, locals);
err("eval");
return Python(ret, "eval");
}
private:
/// Assign object \var obj at the ith slot of tuple
template <typename T>
static std::string tuple_assign(PyObject** ptr, std::size_t& i, T t)
{
Python obj = Python(t);
if constexpr(is_starred<0, T>::value)
{
/// Target size (size of the container to fill)
const std::size_t t_size = PyObject_Size(*ptr);
/// Container size (size of the container to get items from)
const std::size_t c_size = PyObject_Size(obj);
_PyTuple_Resize(ptr, t_size + c_size - 1);
err("tuple");
for (std::size_t index = 0; index < c_size; index++, i++)
PyTuple_SetItem(*ptr, i, PySequence_GetItem(obj, index));
err("tuple");
return std::string("*") + obj.name();
}
else
{
Py_INCREF(obj);
PyTuple_SetItem(*ptr, i++, obj);
err("tuple");
return obj.name();
}
}
/// Collect the arguments of a C++ tuple to put them in a python tuple
template <std::size_t pos, typename ...Args>
static std::string tuple_caller(PyObject** ptr, std::size_t& i, const std::tuple<Args...>& args)
{
std::string name;
if constexpr(pos == 0)
name = tuple_assign(ptr, i, std::get<pos>(args));
else
name = ", " + tuple_assign(ptr, i, std::get<pos>(args));
if constexpr(pos + 1 < sizeof...(Args))
name += tuple_caller<pos + 1>(ptr, i, args);
return name;
}
public:
/// Create a tuple from C++ tuple
template <typename ...Args>
static Python tuple(const std::tuple<Args...>& args)
{
initialize();
constexpr auto size = sizeof...(Args);
auto ptr = PyTuple_New(size);
err("tuple");
if constexpr(sizeof...(Args))
{
std::size_t i = 0;
return Python(ptr, "(" + tuple_caller<0>(&ptr, i, args) + ")");
}
else
return Python(ptr, "()");
}
/// Create a tuple from all the passed arguments
template <typename ...Args>
static Python tuple(Args... args)
{
return tuple(std::tuple(args...));
}
/// Create a tuple from C++ iterable
template <typename Iterable>
static Python tuple(const Iterable& iter)
{
static_assert(is_iterable<Iterable>::value);
initialize();
auto ptr = PyTuple_New(iter.size());
err("tuple");
std::string name;
std::size_t i = 0;
for (auto&& e : iter)
{
if (i > 0)
name += ", ";
name += tuple_assign(&ptr, i, e);
}
return Python(ptr, "[" + name + "]");
}
/// Create a tuple from python iterable
static Python tuple(Python o)
{
assert(o.is_valid());
auto ptr = PySequence_Tuple(o);
err("tuple");
return Python(ptr, "tuple(" + o.name() + ")" );
}
private:
/// Assign object \var obj at the ith slot of list
template <typename T>
static std::string list_assign(PyObject* ptr, T t)
{
Python obj = Python(t);
if constexpr(is_starred<0, T>::value)
{
/// Container size (size of the container to get items from)
const std::size_t c_size = PyObject_Size(obj);
for (std::size_t index = 0; index < c_size; index++)
PyList_Append(ptr, PySequence_GetItem(obj, index));
err("list");
return std::string("*") + obj.name();
}
else
{
Py_INCREF(obj);
PyList_Append(ptr, obj);
err("list");
return obj.name();
}
}
/// Collect the arguments of a C++ tuple to put them in a python list
template <std::size_t pos, typename ...Args>
static std::string list_caller(PyObject* ptr, const std::tuple<Args...>& args)
{
std::string name;
if constexpr(pos == 0)
name = list_assign(ptr, std::get<pos>(args));
else
name = ", " + list_assign(ptr, std::get<pos>(args));
if constexpr(pos + 1 < sizeof...(Args))
name += list_caller<pos + 1>(ptr, args);
return name;
}
public:
/// Create a list from C++ tuple
template <typename ...Args>
static Python list(const std::tuple<Args...>& args)
{
initialize();
auto ptr = PyList_New(0);
err("list");
if constexpr(sizeof...(Args))
return Python(ptr, "[" + list_caller<0>(ptr, args) + "]");
else
return Python(ptr, "[]");
}
/// Create a list from all the passed arguments
template <typename ...Args>
static Python list(Args... args)
{
return list(std::tuple(args...));
}
/// Create a list from C++ iterable
template <typename Iterable>
static Python list(const Iterable& iter)
{
static_assert(is_iterable<Iterable>::value);
initialize();
auto ptr = PyList_New(0);
err("list");
std::string name;
bool first = false;
for (auto&& e : iter)
{
if (first)
name += ", ";
name += list_assign(ptr, e);
first = true;
}
return Python(ptr, "[" + name + "]");
}
/// Create a list from python iterable
static Python list(Python o)
{
assert(o.is_valid());
auto ptr = PySequence_List(o);
err("list");
return Python(ptr, "list(" + o.name() + ")" );
}
private:
/// Collect the args (key, value pairs) and put them into the dict
template <typename K, typename T, typename ...Args>
static std::string dict_assign(Python& dict, K k, T i, Args... items)
{
assert(dict.is_valid());
auto key = Python(k);
auto item = Python(i);
dict[key] = item;
err("dict");
std::string name = key.ref_.name + ": " + item.ref_.name;
if constexpr(sizeof...(Args))
name += ", " + dict_assign(dict, items...);
return name;
}
/// Overload of dict_assign for pair
template <typename K, typename T>
static std::string dict_assign(Python& dict, const std::pair<K, T>& p)
{
assert(dict.is_valid());
auto key = Python(p.first);
auto item = Python(p.second);
dict[key] = item;
err("dict");
return key.ref_.name + ": " + item.ref_.name;
}
public:
/// Create a dictionnary from all the passed objects
template <typename ...Args>
static Python dict(Args... items)
{
initialize();
auto ptr = PyDict_New();
err("dict");
auto obj = Python(ptr, "dict");
if constexpr(sizeof...(Args))
obj.ref_.name = dict_assign(obj, items...);
return obj;
}
/// Overload of dict for iterable
template <typename Iterable>
static Python dict(const Iterable& i)
{
static_assert(is_iterable<Iterable>::value);
initialize();
auto ptr = PyDict_New();
err("dict");
auto obj = Python(ptr, "dict");
bool first = true;
for (const auto& e : i)
{
if (first == false)
obj.ref_.name += ", ";
obj.ref_.name += dict_assign(obj, e);
first = false;
}
return obj;
}
/// Create a dictionnary from passed \var keys iterable and \var values iterable
static Python dict(Python keys, Python values)
{
assert(keys.size() == values.size());
auto ptr = PyDict_New();
err("dict");
auto obj = Python(ptr, "dict(keys = " + keys.name() + ", values = " + values.name() + ")");
const std::size_t size = keys.size();
for (std::size_t i = 0; i < size; i++)
obj[static_cast<Python>(keys[i])] = values[i];
return obj;
}
/// Create a set from the iterable \var o
static Python set(Python o)
{
assert(PyTuple_Check(o) || PyList_Check(o));
auto ptr = PySet_New(o);
err("set");
return Python(ptr, "set(" + o.name() + ")");
}
/*===== CONSTRUCTORS =====*/
template <typename A, typename B>
Python(const std::pair<A, B>& p)
{
*this = tuple(p.first, p.second);
assert(is_valid());
}
template <typename T>
Python(const std::vector<T>& v)
{
*this = list(v);
assert(is_valid());
}
// avoid ambiguouty with vector-like (like string) structures and vector
template <typename T>
Python(const std::initializer_list<T>& v)
{
*this = list(v);
assert(is_valid());
}
template <typename T, std::size_t N>
Python(const std::array<T, N>& v)
{
*this = list(v);
assert(is_valid());
}
template <typename T>
Python(const std::list<T>& v)
{
*this = list(v);
assert(is_valid());
}
template <typename K, typename T>
Python(const std::map<K, T>& v)
{
*this = dict(v);
assert(is_valid());
}
template <typename ...Args>
Python(const std::tuple<Args...>& v)
{
*this = tuple(v);
assert(is_valid());
}
template <typename T>
Python(const std::optional<T>& t)
{
if (t.has_value())
*this = Python(t.value());
else
*this = None;
}
// Generic constructor working with any type of string (as long as python support them)
template <typename charT>
Python(const std::basic_string<charT>& t)
{
initialize();
ref_ = PyRef(PyUnicode_FromKindAndData(sizeof(charT), t.c_str(), t.size()), "\"" + to_string(t) + "\"");
err("Python");
}
template <typename charT>
explicit Python(const charT* t)
: Python(std::basic_string<charT>(t))
{
static_assert(std::is_same<charT, char>::value
|| std::is_same<charT, wchar_t>::value
|| std::is_same<charT, char16_t>::value
|| std::is_same<charT, char32_t>::value);
}
template <typename T>
Python(PyIndexProxy<T> t)
{
*this = t;
}
template <typename T>
Python(Starred<T> t)
{
*this = t;
}
Python(const PyRef& ref)
: ref_(ref)
{}
/// Default constructor
Python(void)
{}
/// Default constructor for nullptr (seamlessly pass nullptr)
Python(std::nullptr_t)
{}
/// Copy constructor
Python(const Python& o)
: ref_(o.ref_)
{}
explicit Python(const std::filesystem::path& t)
{
initialize();
ref_ = PyRef(PyUnicode_FromKindAndData(sizeof(std::filesystem::path::value_type), t.c_str(), t.string().size()), "\"" + to_string(t) + "\"");
err("Python");
}
// unified interface to get rid of ambiguous overloads
template <typename T, typename B = typename std::remove_cv<T>::type>
explicit Python(const T t)
{
// forbid this contructor to supplant the other ones
static_assert(std::is_same<B, PyRef>::value == false
&& std::is_same<B, Python>::value == false
&& std::is_same<B, std::string>::value == false
&& std::is_same<B, std::nullptr_t>::value == false
&& std::is_same<B, PyIndexProxy<std::string>>::value == false
&& std::is_same<B, PyIndexProxy<Python>>::value == false