# $Id: util.py 2133 2006-09-06 18:52:56Z dairiki $
# util.py - utility functions for Myghty
# Copyright (C) 2004, 2005 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of Myghty and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
#
__all__ = ["OrderedDict", "ThreadLocal", "Value", "InheritedDict", "ConstructorClone", "Registry", "WeakValuedRegistry", "SyncDict", "LRUCache", "argdict", "EncodedPath", "pid", "thread_id", "verify_directory", "PrefixArgs", "module", "StringIO"]
try:
import thread as _thread
import threading as _threading
except ImportError:
import dummy_thread as _thread
import dummy_threading as _threading
import weakref, inspect, sha, string, os, UserDict, copy, sys, imp, re, stat, types, time
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def thread_id():
return _thread.get_ident()
def pid():
return os.getpid()
def verify_directory(dir):
"""verifies and creates a directory. tries to
ignore collisions with other threads and processes."""
tries = 0
while not os.access(dir, os.F_OK):
try:
tries += 1
os.makedirs(dir, 0750)
except:
if tries > 5:
raise
def module(name):
"""imports a module, in the ordinary way, by string name"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
class argdict(dict):
"""supports the argument constructor form of dict which doesnt seem to
be present in python 2.2"""
def __init__(self, **params):
dict.__init__(self)
self.update(params)
class Value:
"""allows pass-by-reference operations"""
def __init__(self, value = None): self.value = value
def __call__(self, *arg):
if len(arg):
self.assign(arg[0])
else:
return self.value
def __str__(self):
return str(self.value)
def assign(self, value):
self.value = value
class ThreadLocal:
"""stores a value on a per-thread basis"""
def __init__(self, value = None, default = None, creator = None):
self.dict = {}
self.default = default
self.creator = creator
if value:
self.put(value)
def __call__(self, *arg):
if len(arg):
self.put(arg[0])
else:
return self.get()
def __str__(self):
return str(self.get())
def assign(self, value):
self.dict[_thread.get_ident()] = value
def put(self, value):
self.assign(value)
def exists(self):
return self.dict.has_key(_thread.get_ident())
def get(self, *args, **params):
if not self.dict.has_key(_thread.get_ident()):
if self.default is not None:
self.put(self.default)
elif self.creator is not None:
self.put(self.creator(*args, **params))
return self.dict[_thread.get_ident()]
def remove(self):
del self.dict[_thread.get_ident()]
class OrderedDict(UserDict.DictMixin):
"""A Dictionary that keeps its own internal ordering"""
def __init__(self, values = None):
self.list = []
self.dict = {}
if values is not None:
for val in values:
self.update(val)
def keys(self):
return self.list
def update(self, dict):
for key in dict.keys():
self.__setitem__(key, dict[key])
def values(self):
return map(lambda key: self[key], self.list)
def __iter__(self):
return iter(self.list)
def itervalues(self):
return iter([self[key] for key in self.list])
def iterkeys(self):return self.__iter__()
def iteritems(self):
return iter([(key, self[key]) for key in self.keys()])
def __delitem__(self, key):
del self.dict[key]
del self.list[self.list.index(key)]
def __setitem__(self, key, object):
if not self.has_key(key):
self.list.append(key)
self.dict.__setitem__(key, object)
def __getitem__(self, key):
return self.dict.__getitem__(key)
class InheritedDict(UserDict.DictMixin):
"""a dictionary that can defer lookups to a second dictionary
if the key is not found locally."""
def __init__(self, dict, superfunc):
self.dict = dict
self.superfunc = superfunc
def __call__(self, key = None, value = None):
if key is None and value is None:
return self.dict
elif value is None:
try:
return self.__getitem__(key)
except KeyError:
return None
else:
self.__setitem__(key, value)
def __getitem__(self, key):
dict = self.dict
if dict.has_key(key): return dict[key]
else:
parent = self.superfunc()
if parent is not None:
return parent[key]
raise KeyError(key)
def __setitem__(self, key, value):
self.dict[key] = value
def __delitem__(self, key):
del self.dict[key]
def keys(self):
return self.dict.keys()
def __contains__(self, key):
return self.has_key(key)
def has_key(self, key):
if self.dict.has_key(key):
return True
parent = self.superfunc()
if parent is not None:
return parent.has_key(key)
return False
class ConstructorClone:
"""cloning methods that take additional parameters. one method is a straight shallow copy,
the other recreates the object via its constructor. both methods assume a relationship
between the given parameters and the attribute names of the object."""
def __init__(self, instance, **params):
self.classobj = instance.__class__
self.instance = instance
self.params = params
def copyclone(self):
cl = copy.copy(self.instance)
for key, value in self.params.iteritems():
setattr(cl, key, value)
return cl
# store the argument specs in a static hash
argspecs = {}
def clone(self):
"""creates a new instance of the class using the regular class
constructor. the arguments to the constructor are divined from
inspecting the parameter names, and pulling those parameters from the
original instance's attributes.
this is essentially a quickie cheater way to get a clone of an object
if you can name your instance variables the same as that of the constructor
arguments. """
key = self.classobj.__module__ + "." + self.classobj.__name__
if not ConstructorClone.argspecs.has_key(key):
argspec = inspect.getargspec(self.classobj.__init__.im_func)
argnames = argspec[0] or []
defaultvalues = argspec[3] or []
(requiredargs, namedargs) = (
argnames[0:len(argnames) - len(defaultvalues)],
argnames[len(argnames) - len(defaultvalues):]
)
ConstructorClone.argspecs[key] = (requiredargs, namedargs)
(requiredargs, namedargs) = ConstructorClone.argspecs[key]
newargs = []
newparams = {}
addlparams = self.params.copy()
for arg in requiredargs:
if arg == 'self': continue
elif self.params.has_key(arg):
newargs.append(self.params[arg])
else:
newargs.append(getattr(self.instance, arg))
if addlparams.has_key(arg): del addlparams[arg]
for arg in namedargs:
if addlparams.has_key(arg): del addlparams[arg]
if self.params.has_key(arg):
newparams[arg] = self.params[arg]
else:
if hasattr(self.instance, arg):
newparams[arg] = getattr(self.instance, arg)
else:
raise "instance has no attribute '%s'" % arg
newparams.update(addlparams)
return self.classobj(*newargs, **newparams)
class PrefixArgs:
"""extracts from the given argument dictionary all values with a key '