Duplicating objects

I can duplicate an object by selecting it and then running the command

bpy.ops.object.duplicate(stuff, stuff)

Is there a way to do the same thing without relying on first selecting the object? Like say, a command that accepts an object’s name/handle, or a list of names/handles as an argument?


import bpy
context = bpy.context
scene = context.scene
obj = bpy.data.objects.get("SomeName")
if obj:
    new_obj = obj.copy()
    #copy data part too (check for empty)
    if obj.data:
        new_obj.data = obj.data.copy()
    #link to scene
    scene.objects.link(new_obj)

I gather that such a command doesn’t exist eh?
Thanks for the code!

I’ve already got a similar piece of code, although it felt like a workaround for simply not knowing the proper command I’m supposed to be using… wait a minute … actually, I think I lifted the code from your blog … are you Bat Hat Media?

Ok, here’s a follow-up question… is there a way to simulate alt-d duplicate? (duplicate an object without creating new mesh data). I tried looking up the copy() command here (to see if there’s a ‘share datablock’=True option or something similar) but because the command is accessed through an object, I don’t know what category to look under

I have a script which works but is not scaling very well. I’m trying to find its bottleneck, and I noticed that I’m copying data when I could be linking.

Don’t copy the data block:

import bpy
context = bpy.context
scene = context.scene
obj = bpy.data.objects.get("SomeName")
if obj:
    new_obj = obj.copy()
    #if obj.data:
    #    new_obj.data = obj.data.copy() <|--- don't copy this if you want 'shared' data

    #link to scene
    scene.objects.link(new_obj)

cooooooool

Thanks so much everyone!