1
$\begingroup$

To write a custom operator, an execute(self, context) method must be defined for it. Similarly, a panel needs a draw(self, context) method.

What is the difference between accessing bpy.context directly and accessing the context passed into these methods? In all my testing, they appear to produce exactly the same results.

Thanks!

$\endgroup$
1

1 Answer 1

1
$\begingroup$

bpy.context can differ from context depending on how the operator or panel is invoked. bpy.context will not be changed by an operator override but context will, for example. Always use context rather than bpy.context in a situation where context is passed as an argument.

$\endgroup$
9
  • $\begingroup$ I figured that's a good general rule, but what's a situation where it would make a difference? $\endgroup$ Aug 5, 2022 at 18:18
  • 1
    $\begingroup$ @AnsonSavage said differently: using bpy.context is like "synthesizing" your own context for use in a quick script you might be writing, where as the (self, context) in an operator class is basically a placeholder for the future context you will pass to your operator when you run it. Whenever you do anything in blender there is a context object that is always being updated with new data and every operator takes this context as it's first argument. $\endgroup$
    – Jakemoyo
    Aug 6, 2022 at 1:38
  • 1
    $\begingroup$ So basically when you're just writing out a quick routine to rename some objects or whatever you'll probably have something like import bpy; for obj in bpy.context.selected_objects: # do a thing;. There you use bpy.context. On the other hand, writing an operator class you do something like def execute(self, context): self.obj = context.edit_object; # do a thing. Using the implicit context from invoking the operator. That's the difference. $\endgroup$
    – Jakemoyo
    Aug 6, 2022 at 1:44
  • 1
    $\begingroup$ Fundamentally they are the same thing at the end of the day, but you might run into weirdness where the bpy.context is not exactly referencing the most up to date data as you want, whereas the context that is passed to the operator is guaranteed to be the bleeding edge, so you want to try to use that in relevant situations. $\endgroup$
    – Jakemoyo
    Aug 6, 2022 at 1:47
  • 1
    $\begingroup$ @Jakemoyo Interesting, okay, that makes sense! Yeah, that's the main reason I've been wondering, because in all my addon-writing, I haven't noticed a difference. Thanks!! $\endgroup$ Aug 6, 2022 at 1:52

You must log in to answer this question.

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