The idea of context_push()/Context_pop() is that they bracket the whole code (like the undo_group thing) , so that once you have set it up your code can alter the context without having to worry about it.
Beyond this it becomes a matter of style. Personally, I loathe if/else, because this tends to create code duplicates(*) so you have to maintain two or more branches in parallel. So my way of writing this:
Code:
if(background_type == 1): # foreground color
pdb.gimp_edit_bucket_fill(background, BUCKET_FILL_FG, LAYER_MODE_NORMAL_LEGACY, 100, 0, False, 1, 1)
elif(background_type == 2): # background color
pdb.gimp_edit_bucket_fill(background, BUCKET_FILL_BG, LAYER_MODE_NORMAL_LEGACY, 100, 0, False, 1, 1)
elif(background_type == 3): # other color
pdb.gimp_context_push()
pdb.gimp_context_set_background(background_color) # set new background color
pdb.gimp_edit_bucket_fill(background, BUCKET_FILL_BG, LAYER_MODE_NORMAL_LEGACY, 100, 0, False, 1, 1) # fill background with new color
pdb.gimp_context_pop()
would be:
Code:
gimp.context_push()
# most of your code goes here
color=[gimp.get_foreground(),gimp.get_background(),background_color][background_type-1]
pdb.gimp_edit_bucket_fill(color, BUCKET_FILL_BG, LAYER_MODE_NORMAL_LEGACY, 100, 0, False, 1, 1) # fill background with new color
# some more of your code goes here
gimp.context_pop()
Then you discover that there are better ways to fill the layer, so you need only one change
Code:
gimp.context_push()
# most of your code goes here
color=[gimp.get_foreground(),gimp.get_background(),background_color][background_type-1]
gimp.set_foreground(color)
layer.fill(FILL_FOREGROUND)
# some more of your code goes here
gimp.context_pop()
(I tend to use the object methods instead of the
pdb.* procedures when they exists, this make the code easier to read. To find what they are, do a
dir(gimp),
dir(image, or
dir(layer) in the python console (after initializing
image and
layer of course) . The mapping are usually quite obvious.
(*) this is called the
DRY principle: "don't repeat yourself". The opposite is of course the WET principle: "We enjoy typing"