简体   繁体   中英

Python 2.7 - How to delete a dictionary using a function?

I have the following function in Python 2.7.5.6:

"""
Delete entire *existing* store from memory. Prior to doing so, a backup
copy of the store is saved to disk with the current date and time as
part of the filename:
"""
def drop(store):
    backup(store)
    del store
    ## BUGGY: the store is preserved in its entirety

where store is a dictionary. If I issue every command in the body of the above function in a Python Shell (IDLE), I get the desired behavior. However, calling the function drop() doesn't work; the store dictionary is not deleted and is preserved. Any help would be greatly appreciated!

That is because you are simply deleting the local copy of the dictionary store that you passed in as a parameter. If you want to delete the original dictionary, just call the del(store) method in your code where you actually need to delete store as follows:

def drop(store):
    backup(store)

store = {}
drop(store)
del store

You could make store an object which contains a dictionary; this would give you access to delete it from inside your function:

class Store:
    def __init__(self, data=None):
        self.data = data or {}

    def clear(self):
        backup(self.data)
        self.data = {}

store = Store()

def drop(store):
    store.clear()

You could also do

def drop(local_store):
    global store
    backup(local_store)
    del store

store = {}   
drop(store)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM