depyo 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,6 +48,29 @@ class PythonObject {
48
48
 
49
49
  // TODO: Refactor to use Symbol.toPrimitive() and Object.valueOf()
50
50
 
51
+ toReprString() {
52
+ if (this.ClassName === "Py_String" || this.ClassName === "Py_Unicode") {
53
+ let raw = this.Value;
54
+ if (raw == null || raw.length === 0) return '""';
55
+ raw = raw.toString();
56
+ let escaped = raw
57
+ .replace(/\\/g, '\\\\')
58
+ .replace(/\n/g, '\\n')
59
+ .replace(/\r/g, '\\r')
60
+ .replace(/\t/g, '\\t');
61
+ let quote = '"';
62
+ if (escaped.includes('"')) {
63
+ if (!escaped.includes("'")) {
64
+ quote = "'";
65
+ } else {
66
+ escaped = escaped.replace(/"/g, '\\"');
67
+ }
68
+ }
69
+ return quote + escaped + quote;
70
+ }
71
+ return this.toString();
72
+ }
73
+
51
74
  toString()
52
75
  {
53
76
  switch(this.ClassName) {
@@ -74,8 +97,16 @@ class PythonObject {
74
97
  case "Py_Interned":
75
98
  return this.Value !== null ? this.Value.toString() : "0";
76
99
 
77
- case "Py_Float":
78
- return this.Value !== null ? `${this.Value}${Number.isInteger(this.Value) ? ".0" : ""}` : "0.0";
100
+ case "Py_Float": {
101
+ if (this.Value === null) return "0.0";
102
+ let s = `${this.Value}`;
103
+ // Python rejects `1e+300.0`; only append `.0` when the
104
+ // printed form is pure digits (optional sign).
105
+ if (/^-?\d+$/.test(s)) {
106
+ s += ".0";
107
+ }
108
+ return s;
109
+ }
79
110
 
80
111
  case "Py_VeryLong":
81
112
  if (this.Value) {
@@ -123,10 +154,11 @@ class PythonObject {
123
154
  let res = "(";
124
155
  if (this.Value) {
125
156
  for (let obj of this.Value) {
157
+ const part = obj instanceof PythonObject ? obj.toReprString() : String(obj);
126
158
  if (res != "(") {
127
- res += ", " + obj;
159
+ res += ", " + part;
128
160
  } else {
129
- res += obj;
161
+ res += part;
130
162
  }
131
163
  }
132
164
  res += ")";
@@ -144,8 +176,10 @@ class PythonObject {
144
176
  for (let pair of this.Value) {
145
177
  if (res != "(") {
146
178
  res += ", ";
147
- }
148
- res += pair.key + ": " + pair.value;
179
+ }
180
+ const kPart = pair.key instanceof PythonObject ? pair.key.toReprString() : String(pair.key);
181
+ const vPart = pair.value instanceof PythonObject ? pair.value.toReprString() : String(pair.value);
182
+ res += kPart + ": " + vPart;
149
183
  }
150
184
  res += ")";
151
185
  return res;