Skip to content

Commit 4b21997

Browse files
committed
BUG: Fix environment checking logic for NUMPY_WARN_IF_NO_MEM_POLICY
The logic was reversed accidentally, since the default is to not warn. I would be happy to dig a bit deeper and move the `getenv` to import time (with an small internal helper to set it). Since the `getenv` right now will be called for quite a bit of pythran code currently.
1 parent 9b0b40b commit 4b21997

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

numpy/core/src/multiarray/arrayobject.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,7 @@ array_dealloc(PyArrayObject *self)
503503
}
504504
if (fa->mem_handler == NULL) {
505505
char *env = getenv("NUMPY_WARN_IF_NO_MEM_POLICY");
506-
if ((env == NULL) || (strncmp(env, "1", 1) == 0)) {
506+
if ((env != NULL) && (strncmp(env, "1", 1) == 0)) {
507507
char const * msg = "Trying to dealloc data, but a memory policy "
508508
"is not set. If you take ownership of the data, you must "
509509
"set a base owning the data (e.g. a PyCapsule).";

numpy/core/tests/test_mem_policy.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -357,24 +357,36 @@ def test_new_policy(get_module):
357357
c = np.arange(10)
358358
assert np.core.multiarray.get_handler_name(c) == orig_policy_name
359359

360-
def test_switch_owner(get_module):
360+
@pytest.mark.parametrize("policy", ["0", "1", None])
361+
def test_switch_owner(get_module, policy):
361362
a = get_module.get_array()
362363
assert np.core.multiarray.get_handler_name(a) is None
363364
get_module.set_own(a)
364365
oldval = os.environ.get('NUMPY_WARN_IF_NO_MEM_POLICY', None)
365-
os.environ['NUMPY_WARN_IF_NO_MEM_POLICY'] = "1"
366+
if policy is None:
367+
if 'NUMPY_WARN_IF_NO_MEM_POLICY' in os.environ:
368+
os.environ.pop('NUMPY_WARN_IF_NO_MEM_POLICY')
369+
else:
370+
os.environ['NUMPY_WARN_IF_NO_MEM_POLICY'] = policy
366371
try:
367372
# The policy should be NULL, so we have to assume we can call
368-
# "free"
369-
with assert_warns(RuntimeWarning) as w:
373+
# "free". A warning is given if the policy == "1"
374+
if policy == "1":
375+
with assert_warns(RuntimeWarning) as w:
376+
del a
377+
gc.collect()
378+
else:
370379
del a
371380
gc.collect()
381+
372382
finally:
373383
if oldval is None:
374-
os.environ.pop('NUMPY_WARN_IF_NO_MEM_POLICY')
384+
if 'NUMPY_WARN_IF_NO_MEM_POLICY' in os.environ:
385+
os.environ.pop('NUMPY_WARN_IF_NO_MEM_POLICY')
375386
else:
376387
os.environ['NUMPY_WARN_IF_NO_MEM_POLICY'] = oldval
377388

389+
def test_owner_is_base(get_module):
378390
a = get_module.get_array_with_base()
379391
with pytest.warns(UserWarning, match='warn_on_free'):
380392
del a

0 commit comments

Comments
 (0)