AttributeError: '_RestrictData' object has no attribute 'filepath'

I’m working on a small post-save-hook, which is working pretty nicely only if the file is saved first and then the script is loaded later on. If I install my addon from the file and I save the currently opened new blender project I have this error:

AttributeError: '_RestrictData' object has no attribute 'filepath'

Which comes from the line, where I try to access the filepath data of my blender file:

path = bpy.data.filepath

When I remove my script, save the blender file and then readd my script it works again. So basically my question is:
What is the workaround of this issue? Can an already loaded module reload itself? Or is there some other way to do this properly?
Thanks in advance!

The _RestrictData object indicates that you were trying to access stuff in bpy.data.(…) before ( blender is ready )

I don’t know the technical details but I know that it happens during startup if you access bpy.data prior to register()

The first time blender reads the script is just to gather bl_info and make sure that register() is defined in the script.

After this reading of the file, blender may have other scripts to scan and so it moves on to scan the rest of the files in addons/startup…

Then, after that, if the addon is to be enabled, blender calls the script’s register() ––> and from there it is usually safe to go for bpy.data.(…) or bpy.context.(…)

The line I’m referring to is inside the function which will be registered by blender itself. In my module level there is only 4 functions, two of them is the register and unregister, a dictionary, which is the bl_info and the call of the register. So I guess this shouldn’t be the problem…

Stumped. I guess I’d have to look at the code.

Answered at stackexchange:
AttributeError: ‘_RestrictData’ object has no attribute ‘filepath’

Problem: from … import … as imports _RestrictData permanently, import bpy and bpy.data needs to be used instead

Sorry to bump an old thread, but I’m getting this error message now, except I am using “import bpy” and accessing it via “bpy.data”.

I’m running Blender via the command line, with a python script as an argument. How can I delay the execution of the script to after blender is ready for it to access these areas?