Skip to content

Instantly share code, notes, and snippets.

@obeleh
Created April 16, 2014 07:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obeleh/10820635 to your computer and use it in GitHub Desktop.
Save obeleh/10820635 to your computer and use it in GitHub Desktop.
Python simple deepcopy

A while ago I needed a deepcopy function in python. I found out however that for my usecase I could better build my own. I want to share it so that others might benefit as well.

If the data you're copying is simple data, deepcopy might be overkill. With simple I mean if your data is representable as Json. Let me illustrate with code:

I've used [json-generator](http://www.json-generator.com/ to get some sample json data.)

def deepCopyList(inp):
    for vl in inp:
        if isinstance(vl, list):
            yield list(deepCopyList(vl))
        elif isinstance(vl, dict):
            yield deepCopyDict(vl)

def deepCopyDict(inp):
    outp = inp.copy()
    for ky, vl in outp.iteritems():
        if isinstance(vl, dict):
            outp[ky] = deepCopyDict(vl)      
        elif isinstance(vl, list):
            outp[ky] = list(deepCopyList(vl))  
    return outp

def simpleDeepCopy(inp):
    if isinstance(inp, dict):
        return deepCopyDict(inp)
    elif isinstance(inp, list):
        return deepCopyList(inp)
    else:
        return inp

if __name__ == '__main__':
    import simplejson as json
    import time
    from copy import deepcopy
    fl = open('sample.json', 'r')
    sample = json.load(fl)
    start = time.time()
    for _ in xrange(10000):
        tmp = simpleDeepCopy(sample)
    end = time.time()
    print 'simpleDeepCopy: ' + str(end - start)
    start = time.time()
    for _ in xrange(10000):
        tmp = deepcopy(sample)
    end = time.time()
    print 'copy.deepcopy: ' + str(end - start)

Output

simpleDeepCopy: 0.0132050514221
copy.deepcopy: 2.66142916679

simpleDeepCopy: 0.0128579139709
copy.deepcopy: 2.60736298561
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment