From 958f748e53ec03c8880e9e208498de5a101362b4 Mon Sep 17 00:00:00 2001 From: David Lechner Date: Tue, 13 Dec 2022 12:06:04 -0600 Subject: [PATCH] unix/moduos: Implement 2-arg version of os.getenv(). This adds the `default` argument of `os.getenv(key, default=None)`. Signed-off-by: David Lechner --- ports/unix/moduos.c | 9 ++++++--- tests/cpydiff/modules_os_getenv_argcount.py | 14 -------------- 2 files changed, 6 insertions(+), 17 deletions(-) delete mode 100644 tests/cpydiff/modules_os_getenv_argcount.py diff --git a/ports/unix/moduos.c b/ports/unix/moduos.c index 854ff335faa4..e44ceb677b5c 100644 --- a/ports/unix/moduos.c +++ b/ports/unix/moduos.c @@ -32,14 +32,17 @@ #include "py/runtime.h" #include "py/mphal.h" -STATIC mp_obj_t mp_uos_getenv(mp_obj_t var_in) { - const char *s = getenv(mp_obj_str_get_str(var_in)); +STATIC mp_obj_t mp_uos_getenv(size_t n_args, const mp_obj_t *args) { + const char *s = getenv(mp_obj_str_get_str(args[0])); if (s == NULL) { + if (n_args == 2) { + return args[1]; + } return mp_const_none; } return mp_obj_new_str(s, strlen(s)); } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_uos_getenv_obj, mp_uos_getenv); +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_uos_getenv_obj, 1, 2, mp_uos_getenv); STATIC mp_obj_t mp_uos_putenv(mp_obj_t key_in, mp_obj_t value_in) { const char *key = mp_obj_str_get_str(key_in); diff --git a/tests/cpydiff/modules_os_getenv_argcount.py b/tests/cpydiff/modules_os_getenv_argcount.py deleted file mode 100644 index d7838a92ccba..000000000000 --- a/tests/cpydiff/modules_os_getenv_argcount.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -categories: Modules,os -description: ``getenv`` only allows one argument -cause: Unknown -workaround: Test that the return value is ``None`` -""" -import os - -try: - print(os.getenv("NEW_VARIABLE", "DEFAULT")) -except TypeError: - print("should not get here") - # this assumes NEW_VARIABLE is never an empty variable - print(os.getenv("NEW_VARIABLE") or "DEFAULT")