# How do I get the correct context for Python operators?

I am currently trying to use the operator bpy.ops.sequencer.duplicate() in a python script, but I am having trouble finding the correct context to pass to it, as I am getting the standard RuntimeError: Operator bpy.ops.sequencer.duplicate.poll() failed, context is incorrect error.

How do you find what the required context for a Python operator is?

• – batFINGER Dec 12 '16 at 17:55
• PS you have a link to an unofficial blender fork's documentation. But here this operator is the same. – David Dec 13 '16 at 2:01

After looking through the api documentation, it does not appear that there is a direct way to know which contexts an operator will work in.
Therefore, one way to determine this is to call an operator's poll method in every context to see if the operator will work (brute forcing it). Using this approach, the bpy.ops.sequencer.duplicate will work in the 'SEQUENCE_EDITOR' context, and only the sequence editor.

The script below simply runs through all the areas and polls the operator (line 15).

import bpy

#all the area types except 'EMPTY' from blender.org/api/blender_python_api_current/bpy.types.Area.html#bpy.types.Area.type
types = {'VIEW_3D', 'TIMELINE', 'GRAPH_EDITOR', 'DOPESHEET_EDITOR', 'NLA_EDITOR', 'IMAGE_EDITOR', 'SEQUENCE_EDITOR', 'CLIP_EDITOR', 'TEXT_EDITOR', 'NODE_EDITOR', 'LOGIC_EDITOR', 'PROPERTIES', 'OUTLINER', 'USER_PREFERENCES', 'INFO', 'FILE_BROWSER', 'CONSOLE'}

#save the current area
area = bpy.context.area.type

#try each type
for type in types:
#set the context
bpy.context.area.type = type

#print out context where operator works (change the ops below to check a different operator)
if bpy.ops.sequencer.duplicate.poll():
print(type)

#leave the context where it was
bpy.context.area.type = area

• Too bad there isn't a lookup or cheat sheet, thanks for the awesome work around! – VRM Dec 13 '16 at 2:10
• This would be a cool addon for the text editor. Add a edit box to type in the operator ... :) – Tiles Dec 13 '16 at 8:05