Created
October 25, 2011 15:39
-
-
Save alexbw/1313169 to your computer and use it in GitHub Desktop.
Using shelve for good, not for evil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, shelve | |
# Get the current module (for its namespace, so we can fill it with variables) | |
import sys | |
thismodule = sys.modules[__name__] | |
# Get the hidden directory holding our persistence files | |
persistenceDirectory = os.path.expanduser("~/.mySecretData/") # The directory for our persistent data | |
os.system("mkdir -p " + persistenceDirectory) # Make sure the directory exists | |
pathToStateFile = os.path.join(persistenceDirectory, "stateVariables.db") # a persistent set of variables | |
state = shelve.open(pathToStateFile, flag='c') # opens the state file if it doesn't exist | |
# If we haven't set the state variables before, do it here. | |
# I also like this method, because it lists everything that | |
# we're tracking, and the suggested values/ranges that the variables should take. | |
if not state.has_key('defaults_set'): | |
state['cropModeIsOn'] = False | |
state['boxCenterModeIsOn'] = False | |
state['drawCropRectangle'] = False | |
state['drawCrosshairs'] = False | |
state['upperLeft'] = (0,0) | |
state['lowerRight'] = (0,0) | |
state['boxCenter'] = (0,0) | |
state['defaults_set'] = True | |
# Distribute out the state variables to the module | |
for key, value in zip(state.keys(), state.values()): | |
setattr(thismodule, key, value) | |
# All of the wonderful things that your program does, well, they happen here | |
# ================================================ | |
print drawCropRectangle # first time you run this, this'll print False. Second time, it'll print True. | |
drawCropRectangle = True | |
# ================================================ | |
# Reclaim the state variables from the module | |
for key, value in zip(state.keys(), state.values()): | |
state[key] = getattr(thismodule, key) | |
# Note that you can replace "thismodule" with a class. | |
# There might be an even fancier way to do this by aliasing the dictionary variables into the desired | |
# namespace, but I don't know how to do that. I also don't know if it's a safe/good/easy idea. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment