I wanted to have some global variables in an addon.

But doing so, some parts of the script were not able to access these variables. I had an error message saying I can not use them as they are not initialized.

In this addon, I took some parts of code I have found here, in order to draw on the 3D View. The draw callback of the 'DrawingClass' in this code is able to see these global variables.

But in the operator itself, it does not work.

I have found a workaround setting these variables as class variable of the operator. So... 'it works' (even if the code is not very nice, currently).

But why some execution contexts (the drawing callback) allow to use these globals and not some others (invoke or execute of an operator) ?

I don't put the code directly here, as it is a bit long. But here is the blend file :

The variables are "inactive" and "replaceMode" which can be found in the "grsOperator" class. The script simply replaces the G, R, S keys standard behavior by the corresponding manipulator. On the bottom left of the 3D view, you can click on a square in order to change the mode ("replaceMode") or disable the key interception ("inactive").

  • $\begingroup$ is there a reason why you want to use global variables? i'm only asking because scene properties for instance would allow for similar functionality, and in addition get saved with the blend file $\endgroup$ – aliasguru Jul 30 '16 at 14:52
  • $\begingroup$ @aliasguru, just because this tool options are not related to any object or scene. Yes I should use properties, and probably I should restructure the code in order to put the drawing callback inside the operator (or something like that). But why the variable accessibility changes ? $\endgroup$ – lemon Jul 30 '16 at 14:56
  • 1
    $\begingroup$ Declaring them as globals, eg global inactive will fix the not initialized error. Check out blender.stackexchange.com/a/41329/15543 $\endgroup$ – batFINGER Jul 30 '16 at 16:23
  • $\begingroup$ @batFINGER, if I declare 'global inactive = False', syntax error. If I declare 'global inactive' then 'inactive = False', I still have the problem 'referenced before assignment' $\endgroup$ – lemon Jul 30 '16 at 16:45
  • $\begingroup$ @batFINGER, ok forget it.. I read some Python docs and now I understand what you meant. Thanks ! $\endgroup$ – lemon Jul 30 '16 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.