Merge from 2.5 -r 21285:21515. Thanks Joshua!
[blender.git] / source / blender / python / intern / bpy_interface.c
1
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/stat.h>
6
7 #ifndef WIN32
8 #include <dirent.h>
9 #else
10 #include "BLI_winstuff.h"
11 #endif
12
13 #include <Python.h>
14 #include "compile.h"            /* for the PyCodeObject */
15 #include "eval.h"               /* for PyEval_EvalCode */
16
17 #include "bpy_compat.h"
18
19 #include "bpy_rna.h"
20 #include "bpy_operator.h"
21 #include "bpy_ui.h"
22 #include "bpy_sys.h"
23 #include "bpy_util.h"
24
25 #include "DNA_anim_types.h"
26 #include "DNA_space_types.h"
27 #include "DNA_text_types.h"
28
29 #include "MEM_guardedalloc.h"
30
31 #include "BLI_util.h"
32 #include "BLI_string.h"
33
34 #include "BKE_context.h"
35 #include "BKE_fcurve.h"
36 #include "BKE_text.h"
37
38 #include "BPY_extern.h"
39
40 #include "../generic/bpy_internal_import.h" // our own imports
41 /* external util modules */
42
43 #include "../generic/Mathutils.h"
44 #include "../generic/Geometry.h"
45 #include "../generic/BGL.h"
46
47
48 void BPY_free_compiled_text( struct Text *text )
49 {
50         if( text->compiled ) {
51                 Py_DECREF( ( PyObject * ) text->compiled );
52                 text->compiled = NULL;
53         }
54 }
55
56 /*****************************************************************************
57 * Description: Creates the bpy module and adds it to sys.modules for importing
58 *****************************************************************************/
59 static void bpy_init_modules( void )
60 {
61         PyObject *mod;
62         
63         mod = PyModule_New("bpy");
64         
65         PyModule_AddObject( mod, "data", BPY_rna_module() );
66         /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
67         PyModule_AddObject( mod, "types", BPY_rna_types() );
68         PyModule_AddObject( mod, "props", BPY_rna_props() );
69         PyModule_AddObject( mod, "ops", BPY_operator_module() );
70         PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experimental, consider this a test, especially PyCObject is not meant to be permanent
71         
72         /* add the module so we can import it */
73         PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
74         Py_DECREF(mod);
75
76
77         /* stand alone utility modules not related to blender directly */
78         Geometry_Init("Geometry");
79         Mathutils_Init("Mathutils");
80         BGL_Init("BGL");
81 }
82
83 #if (PY_VERSION_HEX < 0x02050000)
84 PyObject *PyImport_ImportModuleLevel(char *name, void *a, void *b, void *c, int d)
85 {
86         return PyImport_ImportModule(name);
87 }
88 #endif
89
90 void BPY_update_modules( void )
91 {
92         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
93         PyModule_AddObject( mod, "data", BPY_rna_module() );
94         PyModule_AddObject( mod, "types", BPY_rna_types() );
95         PyModule_AddObject( mod, "util", BPY_util_module() );
96
97         /* XXX this will move to bpy.util */
98         PyModule_AddObject( mod, "sys", BPY_sys_module() );
99 }
100
101 /*****************************************************************************
102 * Description: This function creates a new Python dictionary object.
103 *****************************************************************************/
104 static PyObject *CreateGlobalDictionary( bContext *C )
105 {
106         PyObject *mod;
107         PyObject *dict = PyDict_New(  );
108         PyObject *item = PyUnicode_FromString( "__main__" );
109         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
110         PyDict_SetItemString( dict, "__name__", item );
111         Py_DECREF(item);
112         
113         // XXX - evil, need to access context
114         BPy_SetContext(C);
115         
116         // XXX - put somewhere more logical
117         {
118                 PyMethodDef *ml;
119                 static PyMethodDef bpy_prop_meths[] = {
120                         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
121                         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
122                         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
123                         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
124                         {NULL, NULL, 0, NULL}
125                 };
126                 
127                 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
128                         PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
129                 }
130         }
131         
132         /* add bpy to global namespace */
133         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
134         PyDict_SetItemString( dict, "bpy", mod );
135         Py_DECREF(mod);
136         
137         return dict;
138 }
139
140 /* Use this so we can include our own python bundle */
141 #if 0
142 wchar_t* Py_GetPath(void)
143 {
144         int i;
145         static wchar_t py_path[FILE_MAXDIR] = L"";
146         char *dirname= BLI_gethome_folder("python");
147         if(dirname) {
148                 i= mbstowcs(py_path, dirname, FILE_MAXDIR);
149                 printf("py path %s, %d\n", dirname, i);
150         }
151         return py_path;
152 }
153 #endif
154
155
156 /* must be called before Py_Initialize */
157 void BPY_start_python_path(void)
158 {
159         char *py_path_bundle= BLI_gethome_folder("python");
160
161         if(py_path_bundle==NULL)
162                 return;
163
164         /* set the environment path */
165         printf("found bundled python: %s\n", py_path_bundle);
166
167 #if (defined(WIN32) || defined(WIN64))
168 #if defined(FREE_WINDOWS)
169         {
170                 char py_path[FILE_MAXDIR + 11] = "";
171                 sprintf(py_path, "PYTHONPATH=%s", py_path_bundle);
172                 putenv(py_path);
173         }
174 #else
175         _putenv_s("PYTHONPATH", py_path_bundle);
176 #endif
177 #else
178 #ifdef __sgi
179         {
180                 char py_path[FILE_MAXDIR + 11] = "";
181                 sprintf(py_path, "PYTHONPATH=%s", py_path_bundle);
182                 putenv(py_path);
183         }
184 #else
185         setenv("PYTHONPATH", py_path_bundle, 1);
186 #endif
187 #endif
188
189 }
190
191
192 void BPY_start_python( int argc, char **argv )
193 {
194         PyThreadState *py_tstate = NULL;
195         
196         BPY_start_python_path(); /* allow to use our own included python */
197
198         Py_Initialize(  );
199         
200 #if (PY_VERSION_HEX < 0x03000000)
201         PySys_SetArgv( argc, argv);
202 #else
203         /* sigh, why do python guys not have a char** version anymore? :( */
204         {
205                 int i;
206                 PyObject *py_argv= PyList_New(argc);
207
208                 for (i=0; i<argc; i++)
209                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
210
211                 PySys_SetObject("argv", py_argv);
212                 Py_DECREF(py_argv);
213         }
214 #endif
215         
216         /* Initialize thread support (also acquires lock) */
217         PyEval_InitThreads();
218         
219         
220         /* bpy.* and lets us import it */
221         bpy_init_modules(); 
222
223         { /* our own import and reload functions */
224                 PyObject *item;
225                 //PyObject *m = PyImport_AddModule("__builtin__");
226                 //PyObject *d = PyModule_GetDict(m);
227                 PyObject *d = PyEval_GetBuiltins(  );
228                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
229                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
230         }
231         
232         py_tstate = PyGILState_GetThisThreadState();
233         PyEval_ReleaseThread(py_tstate);
234 }
235
236 void BPY_end_python( void )
237 {
238         PyGILState_Ensure(); /* finalizing, no need to grab the state */
239         
240         // free other python data.
241         //BPY_rna_free_types();
242         
243         Py_Finalize(  );
244         
245         return;
246 }
247
248 /* Can run a file or text block */
249 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
250 {
251         PyObject *py_dict, *py_result;
252         PyGILState_STATE gilstate;
253         
254         if (fn==NULL && text==NULL) {
255                 return 0;
256         }
257         
258         //BPY_start_python();
259         
260         gilstate = PyGILState_Ensure();
261
262         BPY_update_modules(); /* can give really bad results if this isnt here */
263         bpy_import_main_set(CTX_data_main(C));
264         
265         py_dict = CreateGlobalDictionary(C);
266
267         if (text) {
268                 
269                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
270                         char *buf = txt_to_buf( text );
271
272                         text->compiled =
273                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
274
275                         MEM_freeN( buf );
276
277                         if( PyErr_Occurred(  ) ) {
278                                 BPy_errors_to_report(reports);
279                                 BPY_free_compiled_text( text );
280                                 PyGILState_Release(gilstate);
281                                 return 0;
282                         }
283                 }
284                 py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
285                 
286         } else {
287                 char pystring[512];
288                 /* TODO - look into a better way to run a file */
289                 sprintf(pystring, "exec(open(r'%s').read())", fn);      
290                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );                  
291         }
292         
293         if (!py_result) {
294                 BPy_errors_to_report(reports);
295         } else {
296                 Py_DECREF( py_result );
297         }
298         
299         Py_DECREF(py_dict);
300         PyGILState_Release(gilstate);
301         bpy_import_main_set(NULL);
302         
303         //BPY_end_python();
304         return py_result ? 1:0;
305 }
306
307
308 /* TODO - move into bpy_space.c ? */
309 /* GUI interface routines */
310
311 /* Copied from Draw.c */
312 static void exit_pydraw( SpaceScript * sc, short err )
313 {
314         Script *script = NULL;
315
316         if( !sc || !sc->script )
317                 return;
318
319         script = sc->script;
320
321         if( err ) {
322                 BPy_errors_to_report(NULL); // TODO, reports
323                 script->flags = 0;      /* mark script struct for deletion */
324                 SCRIPT_SET_NULL(script);
325                 script->scriptname[0] = '\0';
326                 script->scriptarg[0] = '\0';
327 // XXX 2.5              error_pyscript();
328 // XXX 2.5              scrarea_queue_redraw( sc->area );
329         }
330
331 #if 0 // XXX 2.5
332         BPy_Set_DrawButtonsList(sc->but_refs);
333         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
334 #endif
335
336         sc->but_refs = NULL;
337         
338         Py_XDECREF( ( PyObject * ) script->py_draw );
339         Py_XDECREF( ( PyObject * ) script->py_event );
340         Py_XDECREF( ( PyObject * ) script->py_button );
341
342         script->py_draw = script->py_event = script->py_button = NULL;
343 }
344
345 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
346 {
347         if (sc->script==NULL) 
348                 return 0;
349         
350         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
351                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
352                 
353         if (sc->script->py_draw==NULL)
354                 return 0;
355         
356         return 1;
357 }
358
359 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
360 {
361         if (bpy_run_script_init( (bContext *)C, sc)) {
362                 PyGILState_STATE gilstate = PyGILState_Ensure();
363                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
364                 
365                 if (result==NULL)
366                         exit_pydraw(sc, 1);
367                         
368                 PyGILState_Release(gilstate);
369         }
370         return 1;
371 }
372
373 // XXX - not used yet, listeners dont get a context
374 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
375 {
376         if (bpy_run_script_init(C, sc)) {
377                 PyGILState_STATE gilstate = PyGILState_Ensure();
378                 
379                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
380                 
381                 if (result==NULL)
382                         exit_pydraw(sc, 1);
383                         
384                 PyGILState_Release(gilstate);
385         }
386         return 1;
387 }
388
389 void BPY_DECREF(void *pyob_ptr)
390 {
391         Py_DECREF((PyObject *)pyob_ptr);
392 }
393
394 #if 0
395 /* called from the the scripts window, assume context is ok */
396 int BPY_run_python_script_space(const char *modulename, const char *func)
397 {
398         PyObject *py_dict, *py_result= NULL;
399         char pystring[512];
400         PyGILState_STATE gilstate;
401         
402         /* for calling the module function */
403         PyObject *py_func, 
404         
405         gilstate = PyGILState_Ensure();
406         
407         py_dict = CreateGlobalDictionary(C);
408         
409         PyObject *module = PyImport_ImportModule(scpt->script.filename);
410         if (module==NULL) {
411                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
412         }
413         else {
414                 py_func = PyObject_GetAttrString(modulename, func);
415                 if (py_func==NULL) {
416                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
417                 }
418                 else {
419                         Py_DECREF(py_func);
420                         if (!PyCallable_Check(py_func)) {
421                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
422                         }
423                         else {
424                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
425                         }
426                 }
427         }
428         
429         if (!py_result) {
430                 BPy_errors_to_report(NULL); // TODO - reports
431         } else
432                 Py_DECREF( py_result );
433         
434         Py_XDECREF(module);
435         
436         Py_DECREF(py_dict);
437         
438         PyGILState_Release(gilstate);
439         return 1;
440 }
441 #endif
442
443 // #define TIME_REGISTRATION
444
445 #ifdef TIME_REGISTRATION
446 #include "PIL_time.h"
447 #endif
448
449 /* XXX this is temporary, need a proper script registration system for 2.5 */
450 void BPY_run_ui_scripts(bContext *C, int reload)
451 {
452 #ifdef TIME_REGISTRATION
453         double time = PIL_check_seconds_timer();
454 #endif
455         DIR *dir; 
456         struct dirent *de;
457         char *file_extension;
458         char *dirname;
459         char path[FILE_MAX];
460         char *dirs[] = {"io", "ui", NULL};
461         int a;
462         
463         PyGILState_STATE gilstate;
464         PyObject *mod;
465         PyObject *sys_path_orig;
466         PyObject *sys_path_new;
467
468         gilstate = PyGILState_Ensure();
469         
470         // XXX - evil, need to access context
471         BPy_SetContext(C);
472         bpy_import_main_set(CTX_data_main(C));
473
474         for(a=0; dirs[a]; a++) {
475                 dirname= BLI_gethome_folder(dirs[a]);
476
477                 if(!dirname)
478                         continue;
479
480                 dir = opendir(dirname);
481
482                 if(!dir)
483                         continue;
484
485                 /* backup sys.path */
486                 sys_path_orig= PySys_GetObject("path");
487                 Py_INCREF(sys_path_orig); /* dont free it */
488                 
489                 sys_path_new= PyList_New(1);
490                 PyList_SET_ITEM(sys_path_new, 0, PyUnicode_FromString(dirname));
491                 PySys_SetObject("path", sys_path_new);
492                 Py_DECREF(sys_path_new);
493                         
494                 while((de = readdir(dir)) != NULL) {
495                         /* We could stat the file but easier just to let python
496                          * import it and complain if theres a problem */
497
498                         file_extension = strstr(de->d_name, ".py");
499                         
500                         if(file_extension && file_extension[3] == '\0') {
501                                 BLI_strncpy(path, de->d_name, (file_extension - de->d_name) + 1); /* cut off the .py on copy */
502                                 mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
503                                 if (mod) {
504                                         if (reload) {
505                                                 PyObject *mod_orig= mod;
506                                                 mod= PyImport_ReloadModule(mod);
507                                                 Py_DECREF(mod_orig);
508                                         }
509                                 }
510                                 
511                                 if(mod) {
512                                         Py_DECREF(mod); /* could be NULL from reloading */
513                                 } else {
514                                         BPy_errors_to_report(NULL);
515                                         fprintf(stderr, "unable to import \"%s\"  %s/%s\n", path, dirname, de->d_name);
516                                 }
517
518                         }
519                 }
520
521                 closedir(dir);
522
523                 PySys_SetObject("path", sys_path_orig);
524                 Py_DECREF(sys_path_orig);
525         }
526         
527         bpy_import_main_set(NULL);
528         
529         PyGILState_Release(gilstate);
530 #ifdef TIME_REGISTRATION
531         printf("script time %f\n", (PIL_check_seconds_timer()-time));
532 #endif
533 }
534
535 /* ****************************************** */
536 /* Drivers - PyExpression Evaluation */
537
538 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
539 PyObject *bpy_pydriver_Dict = NULL;
540
541 /* For faster execution we keep a special dictionary for pydrivers, with
542  * the needed modules and aliases. 
543  */
544 static int bpy_pydriver_create_dict(void)
545 {
546         PyObject *d, *mod;
547         
548         /* validate namespace for driver evaluation */
549         if (bpy_pydriver_Dict) return -1;
550
551         d = PyDict_New();
552         if (d == NULL) 
553                 return -1;
554         else
555                 bpy_pydriver_Dict = d;
556
557         /* import some modules: builtins, bpy, math, (Blender.noise )*/
558         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
559
560         mod = PyImport_ImportModule("math");
561         if (mod) {
562                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
563                 
564                 /* Only keep for backwards compat! - just import all math into root, they are standard */
565                 PyDict_SetItemString(d, "math", mod);
566                 PyDict_SetItemString(d, "m", mod);
567                 Py_DECREF(mod);
568         } 
569         
570         /* add bpy to global namespace */
571         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
572         if (mod) {
573                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
574                 Py_DECREF(mod);
575         }
576         
577         
578 #if 0 // non existant yet
579         mod = PyImport_ImportModule("Blender.Noise");
580         if (mod) {
581                 PyDict_SetItemString(d, "noise", mod);
582                 PyDict_SetItemString(d, "n", mod);
583                 Py_DECREF(mod);
584         } else {
585                 PyErr_Clear();
586         }
587         
588         /* If there's a Blender text called pydrivers.py, import it.
589          * Users can add their own functions to this module. 
590          */
591         if (G.f & G_DOSCRIPTLINKS) {
592                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
593                 if (mod) {
594                         PyDict_SetItemString(d, "pydrivers", mod);
595                         PyDict_SetItemString(d, "p", mod);
596                         Py_DECREF(mod);
597                 } else {
598                         PyErr_Clear();
599                 }
600         }
601 #endif // non existant yet
602         
603         return 0;
604 }
605
606 /* Update function, it gets rid of pydrivers global dictionary, forcing
607  * BPY_pydriver_eval to recreate it. This function is used to force
608  * reloading the Blender text module "pydrivers.py", if available, so
609  * updates in it reach pydriver evaluation. 
610  */
611 void BPY_pydriver_update(void)
612 {
613         PyGILState_STATE gilstate = PyGILState_Ensure();
614
615         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
616                 PyDict_Clear(bpy_pydriver_Dict);
617                 Py_DECREF(bpy_pydriver_Dict);
618                 bpy_pydriver_Dict = NULL;
619         }
620
621         PyGILState_Release(gilstate);
622
623         return;
624 }
625
626 /* error return function for BPY_eval_pydriver */
627 static float pydriver_error(ChannelDriver *driver) 
628 {
629         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
630                 PyDict_Clear(bpy_pydriver_Dict);
631                 Py_DECREF(bpy_pydriver_Dict);
632                 bpy_pydriver_Dict = NULL;
633         }
634
635         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
636         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
637         
638         BPy_errors_to_report(NULL); // TODO - reports
639
640         return 0.0f;
641 }
642
643 /* This evals py driver expressions, 'expr' is a Python expression that
644  * should evaluate to a float number, which is returned. 
645  */
646 float BPY_pydriver_eval (ChannelDriver *driver)
647 {
648         PyObject *driver_vars=NULL;
649         PyObject *retval;
650         PyGILState_STATE gilstate;
651         
652         DriverTarget *dtar;
653         float result = 0.0f; /* default return */
654         char *expr = NULL;
655         short targets_ok= 1;
656         
657         /* sanity checks - should driver be executed? */
658         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
659                 return result;
660         
661         /* get the py expression to be evaluated */
662         expr = driver->expression; 
663         if ((expr == NULL) || (expr[0]=='\0')) 
664                 return result;
665
666         gilstate = PyGILState_Ensure();
667         
668         /* init global dictionary for py-driver evaluation settings */
669         if (!bpy_pydriver_Dict) {
670                 if (bpy_pydriver_create_dict() != 0) {
671                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
672                         PyGILState_Release(gilstate);
673                         return result;
674                 }
675         }
676         
677         /* add target values to a dict that will be used as '__locals__' dict */
678         driver_vars = PyDict_New(); // XXX do we need to decref this?
679         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
680                 PyObject *driver_arg = NULL;
681                 float tval = 0.0f;
682                 
683                 /* try to get variable value */
684                 tval= driver_get_target_value(driver, dtar);
685                 driver_arg= PyFloat_FromDouble((double)tval);
686                 
687                 /* try to add to dictionary */
688                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
689                         /* this target failed - bad name */
690                         if (targets_ok) {
691                                 /* first one - print some extra info for easier identification */
692                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
693                                 targets_ok= 0;
694                         }
695                         
696                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
697                         BPy_errors_to_report(NULL); // TODO - reports
698                 }
699         }
700         
701         /* execute expression to get a value */
702         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
703         
704         /* decref the driver vars first...  */
705         Py_DECREF(driver_vars);
706         
707         /* process the result */
708         if (retval == NULL) {
709                 result = pydriver_error(driver);
710                 PyGILState_Release(gilstate);
711                 return result;
712         }
713
714         result = (float)PyFloat_AsDouble(retval);
715         Py_DECREF(retval);
716         
717         if ((result == -1) && PyErr_Occurred()) {
718                 result = pydriver_error(driver);
719                 PyGILState_Release(gilstate);
720                 return result;
721         }
722         
723         /* all fine, make sure the "invalid expression" flag is cleared */
724         driver->flag &= ~DRIVER_FLAG_INVALID;
725
726         PyGILState_Release(gilstate);
727
728         return result;
729 }