summaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
authorPaul Sokolovsky <pfalcon@users.sourceforge.net>2014-01-16 23:54:17 +0200
committerPaul Sokolovsky <pfalcon@users.sourceforge.net>2014-01-16 23:54:17 +0200
commit10744dd816b7cc2bfa6a7ea8402ae21aac12838b (patch)
treed1a2e4496b89f5af805568ab6a9076a4d39472ac
parenteea2eb1bb74c59e80deb14872a0aa10d6a69a304 (diff)
downloadmicropython-10744dd816b7cc2bfa6a7ea8402ae21aac12838b.tar.gz
micropython-10744dd816b7cc2bfa6a7ea8402ae21aac12838b.zip
Add empty (false) value testing for strings, tuples, lists, dicts.
-rw-r--r--py/runtime.c18
-rw-r--r--tests/basics/tests/true-value.py27
2 files changed, 45 insertions, 0 deletions
diff --git a/py/runtime.c b/py/runtime.c
index 0da3ced058..d6ef6f9be2 100644
--- a/py/runtime.c
+++ b/py/runtime.c
@@ -297,6 +297,24 @@ int rt_is_true(mp_obj_t arg) {
return 0;
} else if (arg == mp_const_true) {
return 1;
+ } else if (MP_OBJ_IS_QSTR(arg)) {
+ // TODO: \0
+ return *qstr_str(MP_OBJ_QSTR_VALUE(arg)) != 0;
+ } else if (MP_OBJ_IS_TYPE(arg, &str_type)) {
+ // TODO: \0
+ return *qstr_str(mp_obj_str_get(arg)) != 0;
+ } else if (MP_OBJ_IS_TYPE(arg, &list_type)) {
+ uint len;
+ mp_obj_t *dummy;
+ mp_obj_list_get(arg, &len, &dummy);
+ return len != 0;
+ } else if (MP_OBJ_IS_TYPE(arg, &tuple_type)) {
+ uint len;
+ mp_obj_t *dummy;
+ mp_obj_tuple_get(arg, &len, &dummy);
+ return len != 0;
+ } else if (MP_OBJ_IS_TYPE(arg, &dict_type)) {
+ return mp_obj_dict_len(arg) != 0;
} else {
assert(0);
return 0;
diff --git a/tests/basics/tests/true-value.py b/tests/basics/tests/true-value.py
new file mode 100644
index 0000000000..6ba410ddc2
--- /dev/null
+++ b/tests/basics/tests/true-value.py
@@ -0,0 +1,27 @@
+# Test true-ish value handling
+
+if not False:
+ print("False")
+
+if not 0:
+ print("0")
+
+if not "":
+ print("Empty string")
+if "foo":
+ print("Non-empty string")
+
+if not ():
+ print("Empty tuple")
+if ("",):
+ print("Non-empty tuple")
+
+if not []:
+ print("Empty list")
+if [0]:
+ print("Non-empty list")
+
+if not {}:
+ print("Empty dict")
+if {0:0}:
+ print("Non-empty dict")