6
$\begingroup$

I’m trying to make my custom function:

import bpy

def custom_function():
    active = bpy.context.active_object

    # to set cursor location to active object
    bpy.ops.view3d.snap_cursor_to_selected()

custom_fuction()

It's a really simple one, but even that gives me an error:

  ret = _op_call(self.idname_py(), None, kw)

Error:

RuntimeError: Operator bpy.ops.view3d.snap_cursor_to_selected.poll() failed, context is incorrect

I quite don’t get it. Why doesn’t it work?

$\endgroup$
2
  • $\begingroup$ I don't think it is supposed to be "impor bpt". Is it like that in the original? $\endgroup$ May 7, 2022 at 20:09
  • $\begingroup$ I get this error on your code Error: Python: File "E:\blender addons\text_browser.blend\froglet_text_browser.py", line 116 area = next(a for a in bpy.context.screen.areas if a.type == "TEXT_EDITOR", None) ^^^^^^^ SyntaxError: Generator expression must be parenthesized $\endgroup$
    – user151528
    Jul 13, 2022 at 21:18

1 Answer 1

9
$\begingroup$

This operator is only available in the context of the 3D viewport. It means if you're executing it in any other context, it will fail.

You either need to swap areas before and after the execution :

old_type = bpy.context.area.type
bpy.context.area.type = "VIEW_3D"
bpy.ops.view3d.snap_cursor_to_selected()
bpy.context.area.type = old_type

Or you can use an override. Note that you have to have at least one 3D viewport editor open in the interface for it to work.

area = next((a for a in bpy.context.screen.areas if a.type == "VIEW_3D"), None)
if area is not None:
    bpy.ops.view3d.snap_cursor_to_selected({"area": area})

Or starting with Blender V3.2+ :

area = next((a for a in bpy.context.screen.areas if a.type == "VIEW_3D"), None)
if area is not None:
    with bpy.context.temp_override(area=area):
        bpy.ops.view3d.snap_cursor_to_selected()
$\endgroup$
3
  • $\begingroup$ SyntaxError: Generator expression must be parenthesized - should be like area = next((a for a in bpy.context.screen.areas if a.type == "VIEW_3D"), None) if area is not None: with bpy.context.temp_override(area=area): bpy.ops.view3d.snap_cursor_to_selected() $\endgroup$
    – Yu Da Chi
    Nov 26, 2022 at 12:57
  • $\begingroup$ @Oleg try now ? $\endgroup$
    – Gorgious
    Nov 27, 2022 at 21:27
  • $\begingroup$ with parenthesis obviously it's works $\endgroup$
    – Yu Da Chi
    Nov 29, 2022 at 9:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .