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