1

I'm trying to remove null and empty keys from my python object by calling a method from a module.

from file2 import remove_nulls
# initialize object and set attributes
obj.remove_nulls()

In my remove_nulls() method, if I print the resultant object, I can observe that null and empty keys are removed, but after returning from the function, the final object still has the null and empty keys.

def remove_null(feature):
    return json.dumps(del_none(feature.__dict__.copy()))

def del_none(d):
  for key, value in list(d.items()):
    if value is None:
        del d[key]
    elif isinstance(value, dict):
        del_none(value)
  return d 

Can someone help to fine where it went wrong?

siri
  • 125
  • 3
  • 14
  • 4
    Your `return` is inside the `for` loop. It should be after it. – khelwood Oct 11 '18 at 12:11
  • also you need to `return del_none(value)` classic dupe – Jean-François Fabre Oct 11 '18 at 12:18
  • .. and neither of the functions you've included are the ones being called, since you call a method on the object `obj`, and neither the `remove_null(feature)` function or the `del_none(d)` function matches the signature (.. or is part of a class) – MatsLindh Oct 11 '18 at 12:22
  • @MatsLindh, i've not put my exact code, it's just an example to explain the flow, the method is called in my code, if i print the object before return statement, i can see that the null values are removed, but after calling the method in my file, if i print the object i can see that the nulls still exists. – siri Oct 11 '18 at 12:24
  • 1
    @Jean-FrançoisFabre, its not duplicate, please read again. – siri Oct 11 '18 at 12:30

1 Answers1

1

Just too many copies...:

def remove_null(feature):
    return json.dumps(del_none(feature.__dict__.copy()))

that applies del_none on a copy of your object, dumps the proper "cleaned" object, then returns, leaving your object untouched (since you created a copy). You probably need to do just:

def remove_null(feature):
    return json.dumps(del_none(feature.__dict__))

The confusion probably comes from the need to copy the dictionary keys+values to avoid removing items on a dict while iterating on it (which was probably handled here, at the wrong level, then handled at the proper level, but the first copy was not removed)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219