Persisting values as long as Blender remains open, supported?

Is storing persistent values (somewhere) while Blender is still open (ie beyond scene scope) possible in Blender, by other means than having python global variables? Something like this

import bpy
bpy.types.WindowManager.session_integer = bpy.props.IntProperty(
    name = "I want to keep my value in next scene")

print(bpy.context.window_manager.session_integer)
# 0

bpy.context.window_manager.session_integer += 1
print(bpy.context.window_manager.session_integer)
# 1

# Ctrl-N equivalent (File - New)
bpy.ops.wm.read_homefile()

print(bpy.context.window_manager.session_integer)
# 0 (should be 1?)

In the code above, last call prints 0, but I’m looking to keep the 1. Is this supported in Blender? If yes, what is the proper way to do it?

Thanks in advance

Depending on the degree of persistence you’re looking for, you might be able to use AddonPreferences.

there are lots of ways to handle this… you could use a propertygroup and store it with your addon, you could use addonprefs, you could write your variable to a file and read it back, append it to the scene as an attribute, etc.

Can you explain what the issue with global variables is in this particular case?

Storing it on a file would make the data survive beyond the execution of Blender, and appending it to the scene as an attribute does not survive for as long as Blender is open, it will get lost when user changes the scene, but…

you could use a propertygroup and store it with your addon

@testure this is the one I don’t understand what you mean. Can you please elaborate a bit more, maybe this is what I’m looking for?

I haven’t said there’s an issue with global variables. I’m honestly asking in case there is something I may have overlooked.

If this is a best-practices question, I’d first try avoid the need for this entirely… failing that.

  • If the logic is local to a class, you could store the value in a class.
  • Otherwise declare a dictionary, make it’s name explicit global_values or so.
    This way you don’t have to declare global when assigning which can be error prone if you ever miss the global declaration.