Invalid Python expression when using driver with Python script I'm trying to use a python script as an expression in a driver. It was working fine at first and then all of a sudden I get the error message ERROR: Invalid Python expression.



I've tried running the script in the text editor multiple times with no errors, but I get an error in the driver section. Anyone know how to solve this? 

Scrip in text

import bpy

prevTime = 0

###
# Rotates the object with the rotSpeed value in radians/s
###
def rotate(rotSpeed, curRot):
    scn = bpy.context.scene
    curFrame = scn.frame_current
    fps = scn.render.fps

    # Calculate total playtime
    time = curFrame / fps

    # Get delta time
    dt = time - prevTime

    # This will set the current rotation value of the object!!
    newRot = curRot + rotSpeed * dt

    # Set new previous time
    prevTime = time

    return newRot


# Add to driver namaespece to make it accessable     
bpy.app.driver_namespace['RotWithSpeed'] = rotate


EDIT: The error occurs when I add the line "prevTime = time".
Found a solution after a while. Seems like global functions doesn't work the same way in Blender as in raw Python.

I used mini3d's solution found on the blender forum: https://www.blender.org/forum/viewtopic.php?t=27291

Here's a summary of the solution

import bpy

# Define global variables
bpy.types.Scene.prevTime = bpy.props.FloatProperty()

def getSettings():
    settings = bpy.data.scenes.get("Settings")
    if settings is None:
        settings = bpy.data.scenes.new("Settings")

    return settings

def rotate(rotSpeed, curRot):
    .
    .
    getSettings().prevTime = time
    .
    .


EDIT: Global variables do in fact work the same way. The following solution is much cleaner as suggested by batFINGER

The problem was that I tried to edit a global variable in a function without using the keyword "global".

import bpy

# Define global variables
prevTime = 0

def rotate(rotSpeed, curRot):
    # This will give us the ability to edit the global variable
    global prevTime  
    .
    .