Clean up a swath of fixes suggested by 2to3

Fixes from 2to3 include: xrange, ws_comma, repr, reduce,
raise, idioms, has_key, future, filter, exec, callable, apply
This commit is contained in:
R. Tyler Ballance 2009-11-15 17:20:23 -08:00
parent 74961058e9
commit 47fbe57de8
29 changed files with 325 additions and 363 deletions

View File

@ -128,7 +128,7 @@ class CacheRegion(object):
"""
cacheItemID = md5(str(cacheItemID)).hexdigest()
if not self._cacheItems.has_key(cacheItemID):
if cacheItemID not in self._cacheItems:
cacheItem = self._cacheItemClass(
cacheItemID=cacheItemID, cacheStore=self._wrappedCacheDataStore)
self._cacheItems[cacheItemID] = cacheItem

View File

@ -46,12 +46,12 @@ class MemoryCacheStore(AbstractCacheStore):
self._data[key] = (val, time)
def add(self, key, val, time=0):
if self._data.has_key(key):
if key in self._data:
raise Error('a value for key %r is already in the cache'%key)
self._data[key] = (val, time)
def replace(self, key, val, time=0):
if self._data.has_key(key):
if key in self._data:
raise Error('a value for key %r is already in the cache'%key)
self._data[key] = (val, time)

View File

@ -387,12 +387,11 @@ you do have write permission to and re-run the tests.""")
isError = False
dstSources = {}
for b in bundles:
if dstSources.has_key(b.dst):
if b.dst in dstSources:
dstSources[b.dst].append(b.src)
else:
dstSources[b.dst] = [b.src]
keys = dstSources.keys()
keys.sort()
keys = sorted(dstSources.keys())
for dst in keys:
sources = dstSources[dst]
if len(sources) > 1:
@ -537,7 +536,7 @@ you do have write permission to and re-run the tests.""")
return kws
if self.opts.compilerSettingsString:
try:
exec 'settings = getkws(%s)'%self.opts.compilerSettingsString
exec('settings = getkws(%s)'%self.opts.compilerSettingsString)
except:
self.error("There's an error in your --settings option."
"It must be valid Python syntax.\n"

View File

@ -25,8 +25,8 @@ from Cheetah.Utils.Indenter import indentize # an undocumented preprocessor
from Cheetah import ErrorCatchers
from Cheetah import NameMapper
from Cheetah.Parser import Parser, ParseError, specialVarRE, \
STATIC_CACHE, REFRESH_CACHE, SET_LOCAL, SET_GLOBAL,SET_MODULE, \
unicodeDirectiveRE, encodingDirectiveRE,escapedNewlineRE
STATIC_CACHE, REFRESH_CACHE, SET_LOCAL, SET_GLOBAL, SET_MODULE, \
unicodeDirectiveRE, encodingDirectiveRE, escapedNewlineRE
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
VFFSL=valueFromFrameOrSearchList
@ -56,8 +56,8 @@ _DEFAULT_COMPILER_SETTINGS = [
('commentOffset', 1, ''),
('outputRowColComments', True, ''),
('includeBlockMarkers', False, 'Wrap #block\'s in a comment in the template\'s output'),
('blockMarkerStart', ('\n<!-- START BLOCK: ',' -->\n'), ''),
('blockMarkerEnd', ('\n<!-- END BLOCK: ',' -->\n'), ''),
('blockMarkerStart', ('\n<!-- START BLOCK: ', ' -->\n'), ''),
('blockMarkerEnd', ('\n<!-- END BLOCK: ', ' -->\n'), ''),
('defDocStrMsg', 'Autogenerated by Cheetah: The Python-Powered Template Engine', ''),
('setup__str__method', False, ''),
('mainMethodName', 'respond', ''),
@ -379,13 +379,13 @@ class MethodCompiler(GenUtils):
ind = self._indent*2
docStr = (ind + '"""\n' + ind +
('\n' + ind).join([ln.replace('"""',"'''") for ln in self._docStringLines]) +
('\n' + ind).join([ln.replace('"""', "'''") for ln in self._docStringLines]) +
'\n' + ind + '"""\n')
return docStr
## methods for adding code
def addMethDocString(self, line):
self._docStringLines.append(line.replace('%','%%'))
self._docStringLines.append(line.replace('%', '%%'))
def addChunk(self, chunk):
self.commitStrConst()
@ -418,7 +418,7 @@ class MethodCompiler(GenUtils):
self.addChunk("if _v is not None: write(str(_v))")
else:
if self.setting('useFilters'):
self.addChunk("write(_filter(%s%s))"%(chunk,filterArgs))
self.addChunk("write(_filter(%s%s))"%(chunk, filterArgs))
else:
self.addChunk("write(str(%s))"%chunk)
@ -453,7 +453,7 @@ class MethodCompiler(GenUtils):
if not strConst:
return
else:
reprstr = repr(strConst).replace('\\012','\n')
reprstr = repr(strConst).replace('\\012', '\n')
i = 0
out = []
if reprstr.startswith('u'):
@ -545,7 +545,7 @@ class MethodCompiler(GenUtils):
splitPos2 = LVALUE.find('[')
if splitPos1 > 0 and splitPos2==-1:
splitPos = splitPos1
elif splitPos1 > 0 and splitPos1 < max(splitPos2,0):
elif splitPos1 > 0 and splitPos1 < max(splitPos2, 0):
splitPos = splitPos1
else:
splitPos = splitPos2
@ -579,7 +579,7 @@ class MethodCompiler(GenUtils):
def addRepeat(self, expr, lineCol=None):
#the _repeatCount stuff here allows nesting of #repeat directives
self._repeatCount = getattr(self, "_repeatCount", -1) + 1
self.addFor('for __i%s in range(%s)' % (self._repeatCount,expr), lineCol=lineCol)
self.addFor('for __i%s in range(%s)' % (self._repeatCount, expr), lineCol=lineCol)
def addIndentingDirective(self, expr, lineCol=None):
if expr and not expr[-1] == ':':
@ -623,7 +623,7 @@ class MethodCompiler(GenUtils):
self.dedent()
def addElse(self, expr, dedent=True, lineCol=None):
expr = re.sub(r'else[ \f\t]+if','elif', expr)
expr = re.sub(r'else[ \f\t]+if', 'elif', expr)
self.addReIndentingDirective(expr, dedent=dedent, lineCol=lineCol)
def addElif(self, expr, dedent=True, lineCol=None):
@ -660,7 +660,7 @@ class MethodCompiler(GenUtils):
def addYield(self, expr):
assert not self._hasReturnStatement
self._isGenerator = True
if expr.replace('yield','').strip():
if expr.replace('yield', '').strip():
self.addChunk(expr)
else:
self.addChunk('if _dummyTrans:')
@ -727,9 +727,9 @@ class MethodCompiler(GenUtils):
# @@TR: we should add some runtime logging to this
ID = self.nextCacheID()
interval = cacheInfo.get('interval',None)
test = cacheInfo.get('test',None)
customID = cacheInfo.get('id',None)
interval = cacheInfo.get('interval', None)
test = cacheInfo.get('test', None)
customID = cacheInfo.get('id', None)
if customID:
ID = customID
varyBy = cacheInfo.get('varyBy', repr(ID))
@ -896,7 +896,7 @@ class MethodCompiler(GenUtils):
captureDetails.assignTo = assignTo
captureDetails.lineCol = lineCol
self._captureRegionsStack.append((ID,captureDetails)) # attrib of current methodCompiler
self._captureRegionsStack.append((ID, captureDetails)) # attrib of current methodCompiler
self.addChunk('## START CAPTURE REGION: '+ID
+' '+assignTo
+' at line %s, col %s'%lineCol + ' in the source.')
@ -982,13 +982,13 @@ class AutoMethodCompiler(MethodCompiler):
def _setupState(self):
MethodCompiler._setupState(self)
self._argStringList = [ ("self",None) ]
self._argStringList = [ ("self", None) ]
self._streamingEnabled = True
self._isClassMethod = None
self._isStaticMethod = None
def _useKWsDictArgForPassingTrans(self):
alreadyHasTransArg = [argname for argname,defval in self._argStringList
alreadyHasTransArg = [argname for argname, defval in self._argStringList
if argname=='trans']
return (self.methodName()!='respond'
and not alreadyHasTransArg
@ -1015,12 +1015,12 @@ class AutoMethodCompiler(MethodCompiler):
if self._streamingEnabled:
kwargsName = None
positionalArgsListName = None
for argname,defval in self._argStringList:
for argname, defval in self._argStringList:
if argname.strip().startswith('**'):
kwargsName = argname.strip().replace('**','')
kwargsName = argname.strip().replace('**', '')
break
elif argname.strip().startswith('*'):
positionalArgsListName = argname.strip().replace('*','')
positionalArgsListName = argname.strip().replace('*', '')
if not kwargsName and self._useKWsDictArgForPassingTrans():
kwargsName = 'KWS'
@ -1100,7 +1100,7 @@ class AutoMethodCompiler(MethodCompiler):
self.addChunk('return _dummyTrans and trans.response().getvalue() or ""')
def addMethArg(self, name, defVal=None):
self._argStringList.append( (name,defVal) )
self._argStringList.append( (name, defVal) )
def methodSignature(self):
argStringChunks = []
@ -1136,7 +1136,7 @@ if not self._CHEETAH__instanceInitialized:
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
""".replace('\n','\n'+' '*8)
""".replace('\n', '\n'+' '*8)
class ClassCompiler(GenUtils):
methodCompilerClass = AutoMethodCompiler
@ -1173,14 +1173,14 @@ class ClassCompiler(GenUtils):
from the methods of this class!!! or you will be assigning to attributes
of this object instead."""
if self.__dict__.has_key(name):
if name in self.__dict__:
return self.__dict__[name]
elif hasattr(self.__class__, name):
return getattr(self.__class__, name)
elif self._activeMethodsList and hasattr(self._activeMethodsList[-1], name):
return getattr(self._activeMethodsList[-1], name)
else:
raise AttributeError, name
raise AttributeError(name)
def _setupState(self):
self._classDef = None
@ -1333,9 +1333,9 @@ class ClassCompiler(GenUtils):
self._decoratorsForNextMethod.append(decoratorExpr)
def addClassDocString(self, line):
self._classDocStringLines.append( line.replace('%','%%'))
self._classDocStringLines.append( line.replace('%', '%%'))
def addChunkToInit(self,chunk):
def addChunkToInit(self, chunk):
self._initMethChunks.append(chunk)
def addAttribute(self, attribExpr):
@ -1364,7 +1364,7 @@ class ClassCompiler(GenUtils):
'super(%(className)s, self).%(methodName)s(%(argString)s)'%locals())
def addErrorCatcherCall(self, codeChunk, rawCode='', lineCol=''):
if self._placeholderToErrorCatcherMap.has_key(rawCode):
if rawCode in self._placeholderToErrorCatcherMap:
methodName = self._placeholderToErrorCatcherMap[rawCode]
if not self.setting('outputRowColComments'):
self._methodsIndex[methodName].addMethDocString(
@ -1601,14 +1601,14 @@ class ModuleCompiler(SettingsManager, GenUtils):
from the methods of this class!!! or you will be assigning to attributes
of this object instead.
"""
if self.__dict__.has_key(name):
if name in self.__dict__:
return self.__dict__[name]
elif hasattr(self.__class__, name):
return getattr(self.__class__, name)
elif self._activeClassesList and hasattr(self._activeClassesList[-1], name):
return getattr(self._activeClassesList[-1], name)
else:
raise AttributeError, name
raise AttributeError(name)
def _initializeSettings(self):
self.updateSettings(copy.deepcopy(DEFAULT_COMPILER_SETTINGS))
@ -1848,7 +1848,7 @@ class ModuleCompiler(SettingsManager, GenUtils):
self._getActiveClassCompiler().addAttribute(attribName + ' =' + expr)
def addComment(self, comm):
if re.match(r'#+$',comm): # skip bar comments
if re.match(r'#+$', comm): # skip bar comments
return
specialVarMatch = specialVarRE.match(comm)
@ -1935,14 +1935,14 @@ if not hasattr(%(mainClassName)s, '_initCheetahAttributes'):
templateAPIClass._addCheetahPlumbingCodeToClass(%(mainClassName)s)
%(footer)s
""" % {'header':self.moduleHeader(),
'docstring':self.moduleDocstring(),
'specialVars':self.specialVars(),
'imports':self.importStatements(),
'constants':self.moduleConstants(),
'classes':self.classDefs(),
'footer':self.moduleFooter(),
'mainClassName':self._mainClassName,
""" % {'header': self.moduleHeader(),
'docstring': self.moduleDocstring(),
'specialVars': self.specialVars(),
'imports': self.importStatements(),
'constants': self.moduleConstants(),
'classes': self.classDefs(),
'footer': self.moduleFooter(),
'mainClassName': self._mainClassName,
}
self._moduleDef = moduleDef
@ -1976,8 +1976,7 @@ if not hasattr(%(mainClassName)s, '_initCheetahAttributes'):
def specialVars(self):
chunks = []
theVars = self._specialVars
keys = theVars.keys()
keys.sort()
keys = sorted(theVars.keys())
for key in keys:
chunks.append(key + ' = ' + repr(theVars[key]) )
return '\n'.join(chunks)

View File

@ -1,30 +1,14 @@
# $Id: FileUtils.py,v 1.12 2005/11/02 22:26:07 tavis_rudd Exp $
"""File utitilies for Python:
Meta-Data
================================================================================
Author: Tavis Rudd <tavis@damnsimple.com>
License: This software is released for unlimited distribution under the
terms of the MIT license. See the LICENSE file.
Version: $Revision: 1.12 $
Start Date: 2001/09/26
Last Revision Date: $Date: 2005/11/02 22:26:07 $
"""
__author__ = "Tavis Rudd <tavis@damnsimple.com>"
__revision__ = "$Revision: 1.12 $"[11:-2]
from glob import glob
import os
from os import listdir
import os.path
import re
from types import StringType
from tempfile import mktemp
def _escapeRegexChars(txt,
escapeRE=re.compile(r'([\$\^\*\+\.\?\{\}\[\]\(\)\|\\])')):
return escapeRE.sub(r'\\\1' , txt)
return escapeRE.sub(r'\\\1', txt)
def findFiles(*args, **kw):
"""Recursively find all the files matching a glob pattern.
@ -70,7 +54,7 @@ class FileFinder:
def __init__(self, rootPath,
globPatterns=('*',),
ignoreBasenames=('CVS','.svn'),
ignoreBasenames=('CVS', '.svn'),
ignoreDirs=(),
):
@ -220,7 +204,7 @@ class _GenSubberFunc:
return "def subber(m):\n\treturn ''.join([%s])\n" % (self.codeBody())
def subberFunc(self):
exec self.code()
exec(self.code())
return subber
@ -238,11 +222,11 @@ class FindAndReplace:
recordResults=True):
if type(patternOrRE) == StringType:
if isinstance(patternOrRE, basestring):
self._regex = re.compile(patternOrRE)
else:
self._regex = patternOrRE
if type(replacement) == StringType:
if isinstance(replacement, basestring):
self._subber = _GenSubberFunc(replacement).subberFunc()
else:
self._subber = replacement
@ -279,7 +263,7 @@ class FindAndReplace:
self._currFile = file
found = False
if locals().has_key('orig'):
if 'orig' in locals():
del orig
if self._usePgrep:
if os.popen('pgrep "' + pattern + '" ' + file ).read():
@ -289,23 +273,23 @@ class FindAndReplace:
if regex.search(orig):
found = True
if found:
if not locals().has_key('orig'):
if 'orig' not in locals():
orig = open(file).read()
new = regex.sub(subber, orig)
open(file, 'w').write(new)
def _subDispatcher(self, match):
if self._recordResults:
if not self._results.has_key(self._currFile):
if self._currFile not in self._results:
res = self._results[self._currFile] = {}
res['count'] = 0
res['matches'] = []
else:
res = self._results[self._currFile]
res['count'] += 1
res['matches'].append({'contents':match.group(),
'start':match.start(),
'end':match.end(),
res['matches'].append({'contents': match.group(),
'start': match.start(),
'end': match.end(),
}
)
return self._subber(match)
@ -337,10 +321,10 @@ class SourceFileStats:
commentLines += fileStats['commentLines']
totalLines += fileStats['totalLines']
stats = {'codeLines':codeLines,
'blankLines':blankLines,
'commentLines':commentLines,
'totalLines':totalLines,
stats = {'codeLines': codeLines,
'blankLines': blankLines,
'commentLines': commentLines,
'totalLines': totalLines,
}
return stats
@ -364,10 +348,10 @@ class SourceFileStats:
else:
codeLines += 1
stats = {'codeLines':codeLines,
'blankLines':blankLines,
'commentLines':commentLines,
'totalLines':totalLines,
stats = {'codeLines': codeLines,
'blankLines': blankLines,
'commentLines': commentLines,
'totalLines': totalLines,
}
return stats

View File

@ -121,7 +121,7 @@ class MaxLen(Filter):
"""Replace None with '' and cut off at maxlen."""
output = super(MaxLen, self).filter(val, **kw)
if kw.has_key('maxlen') and len(output) > kw['maxlen']:
if 'maxlen' in kw and len(output) > kw['maxlen']:
return output[:kw['maxlen']]
return output
@ -135,7 +135,7 @@ class WebSafe(Filter):
s = s.replace("<", "&lt;")
s = s.replace(">", "&gt;")
# Process the additional transformations if any.
if kw.has_key('also'):
if 'also' in kw:
also = kw['also']
entities = webSafeEntities # Global variable.
for k in also:
@ -166,7 +166,7 @@ class Strip(Filter):
s = super(Strip, self).filter(val, **kw)
result = []
start = 0 # The current line will be s[start:end].
while 1: # Loop through each line.
while True: # Loop through each line.
end = s.find('\n', start) # Find next newline.
if end == -1: # If no more newlines.
break
@ -196,15 +196,15 @@ class StripSqueeze(Filter):
def test():
s1 = "abc <=> &"
s2 = " asdf \n\t 1 2 3\n"
print("WebSafe INPUT:", `s1`)
print(" WebSafe:", `WebSafe().filter(s1)`)
print("WebSafe INPUT:", repr(s1))
print(" WebSafe:", repr(WebSafe().filter(s1)))
print()
print(" Strip INPUT:", `s2`)
print(" Strip:", `Strip().filter(s2)`)
print("StripSqueeze:", `StripSqueeze().filter(s2)`)
print(" Strip INPUT:", repr(s2))
print(" Strip:", repr(Strip().filter(s2)))
print("StripSqueeze:", repr(StripSqueeze().filter(s2)))
print("Unicode:", `EncodeUnicode().filter(u'aoeu12345\u1234')`)
print("Unicode:", repr(EncodeUnicode().filter(u'aoeu12345\u1234')))
if __name__ == "__main__":
test()

View File

@ -114,7 +114,7 @@ def install(templateFileExtensions=('.tmpl',)):
if not _installed:
CheetahDirOwner.templateFileExtensions = templateFileExtensions
import __builtin__
if type(__builtin__.__import__) == types.BuiltinFunctionType:
if isinstance(__builtin__.__import__, types.BuiltinFunctionType):
global __oldimport__
__oldimport__ = __builtin__.__import__
ImportManager._globalOwnerTypes.insert(0, CheetahDirOwner)
@ -129,7 +129,7 @@ def uninstall():
global _installed
if not _installed:
import __builtin__
if type(__builtin__.__import__) == types.MethodType:
if isinstance(__builtin__.__import__, types.MethodType):
__builtin__.__import__ = __oldimport__
global _manager
del _manager

View File

@ -1,6 +1,5 @@
# $Id: ImportManager.py,v 1.6 2007/04/03 01:56:24 tavis_rudd Exp $
"""Provides an emulator/replacement for Python's standard import system.
"""
Provides an emulator/replacement for Python's standard import system.
@@TR: Be warned that Import Hooks are in the deepest, darkest corner of Python's
jungle. If you need to start hacking with this, be prepared to get lost for a
@ -18,37 +17,14 @@ This is a hacked/documented version of Gordon McMillan's iu.py. I have:
- reorganized the code layout to enhance readability
Meta-Data
================================================================================
Author: Tavis Rudd <tavis@damnsimple.com> based on Gordon McMillan's iu.py
License: This software is released for unlimited distribution under the
terms of the MIT license. See the LICENSE file.
Version: $Revision: 1.6 $
Start Date: 2001/03/30
Last Revision Date: $Date: 2007/04/03 01:56:24 $
"""
__author__ = "Tavis Rudd <tavis@damnsimple.com>"
__revision__ = "$Revision: 1.6 $"[11:-2]
##################################################
## DEPENDENCIES
import sys
import imp
import marshal
##################################################
## CONSTANTS & GLOBALS
try:
True,False
except NameError:
True, False = (1==1),(1==0)
_installed = False
STRINGTYPE = type('')
# _globalOwnerTypes is defined at the bottom of this file
_os_stat = _os_path_join = _os_getcwd = _os_path_dirname = None
@ -85,7 +61,7 @@ def _os_bootstrap():
a = a + ':'
return a + b
else:
raise ImportError, 'no os specific module found'
raise ImportError('no os specific module found')
if join is None:
def join(a, b, sep=sep):
@ -184,7 +160,7 @@ class DirOwner(Owner):
if path == '':
path = _os_getcwd()
if not pathIsDir(path):
raise ValueError, "%s is not a directory" % path
raise ValueError("%s is not a directory" % path)
Owner.__init__(self, path)
def getmod(self, nm,
@ -217,7 +193,7 @@ class DirOwner(Owner):
break
if py is None and pyc is None:
return None
while 1:
while True:
if pyc is None or py and pyc[1][8] < py[1][8]:
try:
co = compile(open(py[0], 'r').read()+'\n', py[0], 'exec')
@ -260,7 +236,7 @@ class BuiltinImportDirector(ImportDirector):
def getmod(self, nm, isbuiltin=imp.is_builtin):
if isbuiltin(nm):
mod = imp.load_module(nm, None, nm, ('','',imp.C_BUILTIN))
mod = imp.load_module(nm, None, nm, ('', '', imp.C_BUILTIN))
return mod
return None
@ -273,7 +249,7 @@ class FrozenImportDirector(ImportDirector):
def getmod(self, nm,
isFrozen=imp.is_frozen, loadMod=imp.load_module):
if isFrozen(nm):
mod = loadMod(nm, None, nm, ('','',imp.PY_FROZEN))
mod = loadMod(nm, None, nm, ('', '', imp.PY_FROZEN))
if hasattr(mod, '__path__'):
mod.__importsub__ = lambda name, pname=nm, owner=self: owner.getmod(pname+'.'+name)
return mod
@ -345,7 +321,7 @@ class PathImportDirector(ImportDirector):
def getmod(self, nm):
mod = None
for thing in self.path:
if type(thing) is STRINGTYPE:
if isinstance(thing, basestring):
owner = self._shadowPath.get(thing, -1)
if owner == -1:
owner = self._shadowPath[thing] = self._makeOwner(thing)
@ -420,11 +396,11 @@ class ImportManager:
importernm = globals.get('__name__', '')
if importernm:
if hasattr(_sys_modules_get(importernm), '__path__'):
contexts.insert(0,importernm)
contexts.insert(0, importernm)
else:
pkgnm = packageName(importernm)
if pkgnm:
contexts.insert(0,pkgnm)
contexts.insert(0, pkgnm)
# so contexts is [pkgnm, None] or just [None]
# now break the name being imported up so we get:
# a.b.c -> [a, b, c]
@ -462,7 +438,7 @@ class ImportManager:
#print "importHook done with %s %s %s (case 1)" % (name, globals['__name__'], fromlist)
return sys.modules[nmparts[0]]
del sys.modules[fqname]
raise ImportError, "No module named %s" % fqname
raise ImportError("No module named %s" % fqname)
if fromlist is None:
#print "importHook done with %s %s %s (case 2)" % (name, globals['__name__'], fromlist)
if context:
@ -487,7 +463,7 @@ class ImportManager:
if self.threaded:
self._release()
if not mod:
raise ImportError, "%s not found in %s" % (nm, ctx)
raise ImportError("%s not found in %s" % (nm, ctx))
#print "importHook done with %s %s %s (case 3)" % (name, globals['__name__'], fromlist)
return bottommod
@ -519,7 +495,7 @@ class ImportManager:
if hasattr(mod, '__co__'):
co = mod.__co__
del mod.__co__
exec co in mod.__dict__
exec(co, mod.__dict__)
if fqname == 'thread' and not self.threaded:
## print "thread detected!"
self.setThreaded()

View File

@ -138,7 +138,7 @@ Version: $Revision: 1.32 $
Start Date: 2001/04/03
Last Revision Date: $Date: 2007/12/10 19:20:09 $
"""
from __future__ import generators
__author__ = "Tavis Rudd <tavis@damnsimple.com>," +\
"\nChuck Esterbrook <echuck@mindspring.com>"
__revision__ = "$Revision: 1.32 $"[11:-2]
@ -211,7 +211,7 @@ def _isInstanceOrClass(obj):
def hasKey(obj, key):
"""Determine if 'obj' has 'key' """
if hasattr(obj,'has_key') and obj.has_key(key):
if hasattr(obj, 'has_key') and key in obj:
return True
elif hasattr(obj, key):
return True
@ -219,7 +219,7 @@ def hasKey(obj, key):
return False
def valueForKey(obj, key):
if hasattr(obj, 'has_key') and obj.has_key(key):
if hasattr(obj, 'has_key') and key in obj:
return obj[key]
elif hasattr(obj, key):
return getattr(obj, key)
@ -230,7 +230,7 @@ def _valueForName(obj, name, executeCallables=False):
nameChunks=name.split('.')
for i in range(len(nameChunks)):
key = nameChunks[i]
if hasattr(obj, 'has_key') and obj.has_key(key):
if hasattr(obj, 'has_key') and key in obj:
nextObj = obj[key]
else:
try:
@ -238,7 +238,7 @@ def _valueForName(obj, name, executeCallables=False):
except AttributeError:
_raiseNotFoundException(key, obj)
if executeCallables and callable(nextObj) and not _isInstanceOrClass(nextObj):
if executeCallables and hasattr(nextObj, '__call__') and not _isInstanceOrClass(nextObj):
obj = nextObj()
else:
obj = nextObj
@ -364,7 +364,7 @@ def example():
}
b = 'this is local b'
print(valueForKey(a.dic,'subDict'))
print(valueForKey(a.dic, 'subDict'))
print(valueForName(a, 'dic.item'))
print(valueForName(vars(), 'b'))
print(valueForName(__builtins__, 'dir')())

View File

@ -37,13 +37,13 @@ def escapeRegexChars(txt,
"""Return a txt with all special regular expressions chars escaped."""
return escapeRE.sub(r'\\\1' , txt)
return escapeRE.sub(r'\\\1', txt)
def group(*choices): return '(' + '|'.join(choices) + ')'
def nongroup(*choices): return '(?:' + '|'.join(choices) + ')'
def namedGroup(name, *choices): return '(P:<' + name +'>' + '|'.join(choices) + ')'
def any(*choices): return apply(group, choices) + '*'
def maybe(*choices): return apply(group, choices) + '?'
def any(*choices): return group(*choices) + '*'
def maybe(*choices): return group(*choices) + '?'
##################################################
## CONSTANTS & GLOBALS ##
@ -67,22 +67,22 @@ namechars = identchars + "0123456789"
#operators
powerOp = '**'
unaryArithOps = ('+', '-', '~')
binaryArithOps = ('+', '-', '/', '//','%')
shiftOps = ('>>','<<')
bitwiseOps = ('&','|','^')
binaryArithOps = ('+', '-', '/', '//', '%')
shiftOps = ('>>', '<<')
bitwiseOps = ('&', '|', '^')
assignOp = '='
augAssignOps = ('+=','-=','/=','*=', '**=','^=','%=',
'>>=','<<=','&=','|=', )
augAssignOps = ('+=', '-=', '/=', '*=', '**=', '^=', '%=',
'>>=', '<<=', '&=', '|=', )
assignmentOps = (assignOp,) + augAssignOps
compOps = ('<','>','==','!=','<=','>=', '<>', 'is', 'in',)
booleanOps = ('and','or','not')
compOps = ('<', '>', '==', '!=', '<=', '>=', '<>', 'is', 'in',)
booleanOps = ('and', 'or', 'not')
operators = (powerOp,) + unaryArithOps + binaryArithOps \
+ shiftOps + bitwiseOps + assignmentOps \
+ compOps + booleanOps
delimeters = ('(',')','{','}','[',']',
',','.',':',';','=','`') + augAssignOps
delimeters = ('(', ')', '{', '}', '[', ']',
',', '.', ':', ';', '=', '`') + augAssignOps
keywords = ('and', 'del', 'for', 'is', 'raise',
@ -131,7 +131,7 @@ for start, end in tripleQuotedStringPairs.items():
WS = r'[ \f\t]*'
EOL = r'\r\n|\n|\r'
EOLZ = EOL + r'|\Z'
escCharLookBehind = nongroup(r'(?<=\A)',r'(?<!\\)')
escCharLookBehind = nongroup(r'(?<=\A)', r'(?<!\\)')
nameCharLookAhead = r'(?=[A-Za-z_])'
identRE=re.compile(r'[a-zA-Z_][a-zA-Z_0-9]*')
EOLre=re.compile(r'(?:\r\n|\r|\n)')
@ -148,8 +148,8 @@ escapedNewlineRE = re.compile(r'(?<!\\)\\n')
directiveNamesAndParsers = {
# importing and inheritance
'import':None,
'from':None,
'import': None,
'from': None,
'extends': 'eatExtends',
'implements': 'eatImplements',
'super': 'eatSuper',
@ -162,7 +162,7 @@ directiveNamesAndParsers = {
'filter': 'eatFilter',
'echo': None,
'silent': None,
'transform' : 'eatTransform',
'transform': 'eatTransform',
'call': 'eatCall',
'arg': 'eatCallArg',
@ -226,7 +226,7 @@ endDirectiveNamesAndHandlers = {
'call': None, # has short-form
'capture': None, # has short-form
'filter': None,
'errorCatcher':None,
'errorCatcher': None,
'while': None, # has short-form
'for': None, # has short-form
'if': None, # has short-form
@ -270,16 +270,16 @@ class ParseError(ValueError):
## get the surrounding lines
lines = stream.splitlines()
prevLines = [] # (rowNum, content)
for i in range(1,4):
for i in range(1, 4):
if row-1-i <=0:
break
prevLines.append( (row-i,lines[row-1-i]) )
prevLines.append( (row-i, lines[row-1-i]) )
nextLines = [] # (rowNum, content)
for i in range(1,4):
for i in range(1, 4):
if not row-1+i < len(lines):
break
nextLines.append( (row+i,lines[row-1+i]) )
nextLines.append( (row+i, lines[row-1+i]) )
nextLines.reverse()
## print the main message
@ -930,7 +930,7 @@ class _LowLevelParser(SourceReader):
argStringBits = ['(']
addBit = argStringBits.append
while 1:
while True:
if self.atEnd():
open = enclosures[-1][0]
close = closurePairsRev[open]
@ -975,7 +975,7 @@ class _LowLevelParser(SourceReader):
else:
beforeTokenPos = self.pos()
token = self.getPyToken()
if token in ('{','(','['):
if token in ('{', '(', '['):
self.rev()
token = self.getExpression(enclosed=True)
token = self.transformToken(token, beforeTokenPos)
@ -1015,7 +1015,7 @@ class _LowLevelParser(SourceReader):
useNameMapper_orig = self.setting('useNameMapper')
self.setSetting('useNameMapper', useNameMapper)
while 1:
while True:
if self.atEnd():
raise ParseError(
self, msg="EOF was reached before a matching ')'"+
@ -1053,7 +1053,7 @@ class _LowLevelParser(SourceReader):
else:
beforeTokenPos = self.pos()
token = self.getPyToken()
if token in ('{','(','['):
if token in ('{', '(', '['):
self.rev()
token = self.getExpression(enclosed=True)
token = self.transformToken(token, beforeTokenPos)
@ -1094,7 +1094,7 @@ class _LowLevelParser(SourceReader):
srcLen = len(self)
exprBits = []
while 1:
while True:
if self.atEnd():
if enclosures:
open = enclosures[-1][0]
@ -1303,8 +1303,8 @@ class _LowLevelParser(SourceReader):
expr = expr[:-1]
rawPlaceholder=self[startPos: self.pos()]
expr = self._applyExpressionFilters(expr,'placeholder',
rawExpr=rawPlaceholder,startPos=startPos)
expr = self._applyExpressionFilters(expr, 'placeholder',
rawExpr=rawPlaceholder, startPos=startPos)
for callback in self.setting('postparsePlaceholderHooks'):
callback(parser=self)
@ -1347,11 +1347,11 @@ class _HighLevelParser(_LowLevelParser):
def _initDirectives(self):
def normalizeParserVal(val):
if isinstance(val, (str,unicode)):
if isinstance(val, (str, unicode)):
handler = getattr(self, val)
elif type(val) in (ClassType, TypeType):
handler = val(self)
elif callable(val):
elif hasattr(val, '__call__'):
handler = val
elif val is None:
handler = val
@ -1362,11 +1362,11 @@ class _HighLevelParser(_LowLevelParser):
normalizeHandlerVal = normalizeParserVal
_directiveNamesAndParsers = directiveNamesAndParsers.copy()
customNamesAndParsers = self.setting('directiveNamesAndParsers',{})
customNamesAndParsers = self.setting('directiveNamesAndParsers', {})
_directiveNamesAndParsers.update(customNamesAndParsers)
_endDirectiveNamesAndHandlers = endDirectiveNamesAndHandlers.copy()
customNamesAndHandlers = self.setting('endDirectiveNamesAndHandlers',{})
customNamesAndHandlers = self.setting('endDirectiveNamesAndHandlers', {})
_endDirectiveNamesAndHandlers.update(customNamesAndHandlers)
self._directiveNamesAndParsers = {}
@ -1381,21 +1381,21 @@ class _HighLevelParser(_LowLevelParser):
continue
self._endDirectiveNamesAndHandlers[name] = normalizeHandlerVal(val)
self._closeableDirectives = ['def','block','closure','defmacro',
self._closeableDirectives = ['def', 'block', 'closure', 'defmacro',
'call',
'capture',
'cache',
'filter',
'if','unless',
'for','while','repeat',
'if', 'unless',
'for', 'while', 'repeat',
'try',
]
for directiveName in self.setting('closeableDirectives',[]):
for directiveName in self.setting('closeableDirectives', []):
self._closeableDirectives.append(directiveName)
macroDirectives = self.setting('macroDirectives',{})
macroDirectives = self.setting('macroDirectives', {})
macroDirectives['i18n'] = I18n
@ -1512,7 +1512,7 @@ class _HighLevelParser(_LowLevelParser):
self.getMultiLineCommentStartToken()
endPos = startPos = self.pos()
level = 1
while 1:
while True:
endPos = self.pos()
if self.atEnd():
break
@ -1579,8 +1579,8 @@ class _HighLevelParser(_LowLevelParser):
del assert raise
silent echo
import from'''.split()
_directiveHandlerNames = {'import':'addImportStatement',
'from':'addImportStatement', }
_directiveHandlerNames = {'import': 'addImportStatement',
'from': 'addImportStatement', }
def eatDirective(self):
directiveName = self.matchDirective()
self._filterDisabledDirectives(directiveName)
@ -1927,8 +1927,8 @@ class _HighLevelParser(_LowLevelParser):
startPos = self.pos()
methodName, rawSignature = self._eatDefOrBlock('block')
self._compiler._blockMetaData[methodName] = {
'raw':rawSignature,
'lineCol':self.getRowCol(startPos),
'raw': rawSignature,
'lineCol': self.getRowCol(startPos),
}
def eatClosure(self):
@ -1937,7 +1937,7 @@ class _HighLevelParser(_LowLevelParser):
def _eatDefOrBlock(self, directiveName):
# filtered
assert directiveName in ('def','block','closure')
assert directiveName in ('def', 'block', 'closure')
isLineClearToStartToken = self.isLineClearToStartToken()
endOfFirstLinePos = self.findEOL()
startPos = self.pos()
@ -2230,15 +2230,15 @@ class _HighLevelParser(_LowLevelParser):
else:
argsList=[]
assert not self._directiveNamesAndParsers.has_key(macroName)
argsList.insert(0, ('src',None))
argsList.append(('parser','None'))
argsList.append(('macros','None'))
argsList.append(('compilerSettings','None'))
argsList.append(('isShortForm','None'))
argsList.append(('EOLCharsInShortForm','None'))
argsList.append(('startPos','None'))
argsList.append(('endPos','None'))
assert macroName not in self._directiveNamesAndParsers
argsList.insert(0, ('src', None))
argsList.append(('parser', 'None'))
argsList.append(('macros', 'None'))
argsList.append(('compilerSettings', 'None'))
argsList.append(('isShortForm', 'None'))
argsList.append(('EOLCharsInShortForm', 'None'))
argsList.append(('startPos', 'None'))
argsList.append(('endPos', 'None'))
if self.matchColonForSingleLineShortFormDirective():
self.advance() # skip over :
@ -2254,8 +2254,8 @@ class _HighLevelParser(_LowLevelParser):
#print argsList
normalizedMacroSrc = ''.join(
['%def callMacro('+','.join([defv and '%s=%s'%(n,defv) or n
for n,defv in argsList])
['%def callMacro('+','.join([defv and '%s=%s'%(n, defv) or n
for n, defv in argsList])
+')\n',
macroSrc,
'%end def'])
@ -2266,9 +2266,9 @@ class _HighLevelParser(_LowLevelParser):
compilerSettings = self.setting('compilerSettingsForDefMacro', default={})
searchListForMacros = self.setting('searchListForDefMacro', default=[])
searchListForMacros = list(searchListForMacros) # copy to avoid mutation bugs
searchListForMacros.append({'macros':self._macros,
'parser':self,
'compilerSettings':self.settings(),
searchListForMacros.append({'macros': self._macros,
'parser': self,
'compilerSettings': self.settings(),
})
templateAPIClass._updateSettingsWithPreprocessTokens(
@ -2328,12 +2328,12 @@ class _HighLevelParser(_LowLevelParser):
else:
def getArgs(*pargs, **kws):
return pargs, kws
exec 'positionalArgs, kwArgs = getArgs(%(args)s)'%locals()
exec('positionalArgs, kwArgs = getArgs(%(args)s)'%locals())
assert not kwArgs.has_key('src')
assert 'src' not in kwArgs
kwArgs['src'] = srcBlock
if type(macro)==new.instancemethod:
if isinstance(macro, new.instancemethod):
co = macro.im_func.func_code
elif (hasattr(macro, '__call__')
and hasattr(macro.__call__, 'im_func')):

View File

@ -103,7 +103,7 @@ definition.""")
if self._CHEETAH__isControlledByWebKit:
return super(Servlet, self).serverSidePath(path)
elif path:
return normpath(abspath(path.replace("\\",'/')))
return normpath(abspath(path.replace("\\", '/')))
elif hasattr(self, '_filePath') and self._filePath:
return normpath(abspath(self._filePath))
else:

View File

@ -34,8 +34,8 @@ def mergeNestedDictionaries(dict1, dict2, copy=False, deepcopy=False):
elif deepcopy:
dict1 = copyModule.deepcopy(dict1)
for key,val in dict2.iteritems():
if dict1.has_key(key) and isinstance(val, dict) and isinstance(dict1[key], dict):
for key, val in dict2.iteritems():
if key in dict1 and isinstance(val, dict) and isinstance(dict1[key], dict):
dict1[key] = mergeNestedDictionaries(dict1[key], val)
else:
dict1[key] = val
@ -104,11 +104,11 @@ class _SettingsCollector(object):
def readSettingsFromPySrcStr(self, theString):
"""Return a dictionary of the settings in a Python src string."""
globalsDict = {'True':(1==1),
'False':(0==1),
globalsDict = {'True': (1==1),
'False': (0==1),
}
newSettings = {'self':self}
exec (theString+os.linesep) in globalsDict, newSettings
exec((theString+os.linesep), globalsDict, newSettings)
del newSettings['self']
module = new.module('temp_settings_module')
module.__dict__.update(newSettings)
@ -154,7 +154,7 @@ class _SettingsCollector(object):
newSettings[s] = {}
for o in p.options(s):
if o != '__name__':
newSettings[s][o] = p.get(s,o)
newSettings[s][o] = p.get(s, o)
## loop through new settings -> deal with global settings, numbers,
## booleans and None ++ also deal with 'importSettings' commands
@ -163,7 +163,7 @@ class _SettingsCollector(object):
for key, val in subDict.items():
if convert:
if val.lower().startswith('python:'):
subDict[key] = eval(val[7:],{},{})
subDict[key] = eval(val[7:], {}, {})
if val.lower() == 'none':
subDict[key] = None
if val.lower() == 'true':
@ -265,7 +265,7 @@ class SettingsManager(_SettingsCollector):
newSettings = self.readSettingsFromPySrcStr(theString)
self.updateSettings(newSettings,
merge=newSettings.get('mergeSettings',merge) )
merge=newSettings.get('mergeSettings', merge) )
def updateSettingsFromConfigFileObj(self, inFile, convert=True, merge=True):
@ -276,7 +276,7 @@ class SettingsManager(_SettingsCollector):
newSettings = self.readSettingsFromConfigFileObj(inFile, convert=convert)
self.updateSettings(newSettings,
merge=newSettings.get('mergeSettings',merge))
merge=newSettings.get('mergeSettings', merge))
def updateSettingsFromConfigStr(self, configStr, convert=True, merge=True):
"""See the docstring for .updateSettingsFromConfigFile()
@ -286,5 +286,5 @@ class SettingsManager(_SettingsCollector):
inFile = StringIO(configStr)
newSettings = self.readSettingsFromConfigFileObj(inFile, convert=convert)
self.updateSettings(newSettings,
merge=newSettings.get('mergeSettings',merge))
merge=newSettings.get('mergeSettings', merge))

View File

@ -160,7 +160,7 @@ class SourceReader:
self._posTobookmarkMap[self._pos] = name
def hasBookmark(self, name):
return self._bookmarks.has_key(name)
return name in self._bookmarks
def gotoBookmark(self, name):
if not self.hasBookmark(name):
@ -247,7 +247,7 @@ class SourceReader:
if pos == None:
pos = self._pos
src = self.src()
return max(src.rfind('\n',0,pos)+1, src.rfind('\r',0,pos)+1, 0)
return max(src.rfind('\n', 0, pos)+1, src.rfind('\r', 0, pos)+1, 0)
def findEOL(self, pos=None, gobble=False):
if pos == None:

View File

@ -25,7 +25,7 @@ from types import StringType, ClassType
try:
from types import StringTypes
except ImportError:
StringTypes = (types.StringType,types.UnicodeType)
StringTypes = (types.StringType, types.UnicodeType)
try:
from threading import Lock
@ -84,15 +84,14 @@ def hashList(l):
return hash(tuple(hashedList))
def hashDict(d):
items = d.items()
items.sort()
items = sorted(d.items())
hashedList = []
for k, v in items:
if isinstance(v, dict):
v = hashDict(v)
elif isinstance(v, list):
v = hashList(v)
hashedList.append((k,v))
hashedList.append((k, v))
return hash(tuple(hashedList))
@ -106,7 +105,7 @@ def _genUniqueModuleName(baseModuleName):
finalName = baseModuleName
else:
finalName = ('cheetah_%s_%s_%s'%(baseModuleName,
str(time.time()).replace('.','_'),
str(time.time()).replace('.', '_'),
str(randrange(10000, 99999))))
return finalName
@ -276,8 +275,8 @@ class Template(Servlet):
'_getTemplateAPIClassForIncludeDirectiveCompilation',
)
_CHEETAH_requiredCheetahClassMethods = ('subclass',)
_CHEETAH_requiredCheetahClassAttributes = ('cacheRegionClass','cacheStore',
'cacheStoreIdPrefix','cacheStoreClass')
_CHEETAH_requiredCheetahClassAttributes = ('cacheRegionClass', 'cacheStore',
'cacheStoreIdPrefix', 'cacheStoreClass')
## the following are used by .compile(). Most are documented in its docstring.
_CHEETAH_cacheModuleFilesForTracebacks = False
@ -781,7 +780,7 @@ class Template(Servlet):
##
try:
co = compile(generatedModuleCode, __file__, 'exec')
exec co in mod.__dict__
exec(co, mod.__dict__)
except SyntaxError, e:
try:
parseError = genParserErrorFromPythonException(
@ -860,7 +859,7 @@ class Template(Servlet):
if hasattr(arg, 'preprocess'):
return arg
elif callable(arg):
elif hasattr(arg, '__call__'):
class WrapperPreprocessor:
def preprocess(self, source, file):
return arg(source, file)
@ -903,7 +902,7 @@ class Template(Servlet):
(settings.placeholderToken,
settings.directiveToken) = normalizeTokens(settings.tokens)
if (not getattr(settings,'compilerSettings', None)
if (not getattr(settings, 'compilerSettings', None)
and not getattr(settings, 'placeholderToken', None) ):
raise TypeError(
@ -992,7 +991,7 @@ class Template(Servlet):
or concreteTemplateClass.__str__ is object.__str__):
mainMethNameAttr = '_mainCheetahMethod_for_'+concreteTemplateClass.__name__
mainMethName = getattr(concreteTemplateClass,mainMethNameAttr, None)
mainMethName = getattr(concreteTemplateClass, mainMethNameAttr, None)
if mainMethName:
def __str__(self):
rc = getattr(self, mainMethName)()
@ -1014,7 +1013,7 @@ class Template(Servlet):
def __str__(self):
rc = None
if hasattr(self, mainMethNameAttr):
rc = getattr(self,mainMethNameAttr)()
rc = getattr(self, mainMethNameAttr)()
elif hasattr(self, 'respond'):
rc = self.respond()
else:
@ -1024,7 +1023,7 @@ class Template(Servlet):
return rc
def __unicode__(self):
if hasattr(self, mainMethNameAttr):
return getattr(self,mainMethNameAttr)()
return getattr(self, mainMethNameAttr)()
elif hasattr(self, 'respond'):
return self.respond()
else:
@ -1356,7 +1355,7 @@ class Template(Servlet):
"""
try:
return valueFromSearchList(self.searchList(), varName.replace('$',''), autoCall)
return valueFromSearchList(self.searchList(), varName.replace('$', ''), autoCall)
except NotFound:
if default is not Unspecified:
return default
@ -1367,7 +1366,7 @@ class Template(Servlet):
"""Test if a variable name exists in the searchList.
"""
try:
valueFromSearchList(self.searchList(), varName.replace('$',''), autoCall)
valueFromSearchList(self.searchList(), varName.replace('$', ''), autoCall)
return True
except NotFound:
return False
@ -1416,7 +1415,7 @@ class Template(Servlet):
various protocols, as PHP allows with its 'URL fopen wrapper'
"""
fp = open(path,'r')
fp = open(path, 'r')
output = fp.read()
fp.close()
return output
@ -1500,7 +1499,7 @@ class Template(Servlet):
if errorCatcher:
if isinstance(errorCatcher, basestring):
errorCatcherClass = getattr(ErrorCatchers, errorCatcher)
elif type(errorCatcher) == ClassType:
elif isinstance(errorCatcher, ClassType):
errorCatcherClass = errorCatcher
self._CHEETAH__errorCatcher = ec = errorCatcherClass(self)
@ -1557,7 +1556,7 @@ class Template(Servlet):
"""Called at runtime to handle #include directives.
"""
_includeID = srcArg
if not self._CHEETAH__cheetahIncludes.has_key(_includeID):
if _includeID not in self._CHEETAH__cheetahIncludes:
if not raw:
if includeFrom == 'file':
source = None
@ -1575,7 +1574,7 @@ class Template(Servlet):
# Template class to be used for compilation so compilerSettings
# can be changed.
compiler = self._getTemplateAPIClassForIncludeDirectiveCompilation(source, file)
nestedTemplateClass = compiler.compile(source=source,file=file)
nestedTemplateClass = compiler.compile(source=source, file=file)
nestedTemplate = nestedTemplateClass(_preBuiltSearchList=self.searchList(),
_globalSetVars=self._CHEETAH__globalSetVars)
# Set the inner template filters to the initial filter of the
@ -1817,8 +1816,8 @@ class Template(Servlet):
raise TypeError("arg 'src' invalid")
sources = source + 's'
converters = {
'' : _Converter('string', None, default, default ),
'int' : _Converter('int', int, defaultInt, badInt ),
'': _Converter('string', None, default, default ),
'int': _Converter('int', int, defaultInt, badInt ),
'float': _Converter('float', float, defaultFloat, badFloat), }
#pprint.pprint(locals()); return {}
dic = {} # Destination.
@ -1860,16 +1859,16 @@ def genParserErrorFromPythonException(source, file, generatedPyCode, exception):
lines = generatedPyCode.splitlines()
prevLines = [] # (i, content)
for i in range(1,4):
for i in range(1, 4):
if pyLineno-i <=0:
break
prevLines.append( (pyLineno+1-i,lines[pyLineno-i]) )
prevLines.append( (pyLineno+1-i, lines[pyLineno-i]) )
nextLines = [] # (i, content)
for i in range(1,4):
for i in range(1, 4):
if not pyLineno+i < len(lines):
break
nextLines.append( (pyLineno+i,lines[pyLineno+i]) )
nextLines.append( (pyLineno+i, lines[pyLineno+i]) )
nextLines.reverse()
report = 'Line|Python Code\n'
report += '----|-------------------------------------------------------------\n'
@ -1916,7 +1915,7 @@ def genParserErrorFromPythonException(source, file, generatedPyCode, exception):
message = '\n'.join(message)
reader = SourceReader(source, filename=filename)
return ParseError(reader, message, lineno=lineno,col=col)
return ParseError(reader, message, lineno=lineno, col=col)
# vim: shiftwidth=4 tabstop=4 expandtab

View File

@ -58,7 +58,7 @@ class CmdLineIface:
sys.exit(2)
for o, a in self._opts:
if o in ('-h','--help'):
if o in ('-h', '--help'):
print(self.usage())
sys.exit()
if o == '--env':
@ -100,8 +100,8 @@ and collect the output. It can prepend the shell ENVIRONMENT or a pickled
Python dictionary to the template's $placeholder searchList, overriding the
defaults for the $placeholders.
""" % {'scriptName':self._scriptName,
'Version':Version,
""" % {'scriptName': self._scriptName,
'Version': Version,
}
# vim: shiftwidth=4 tabstop=4 expandtab

View File

@ -62,7 +62,7 @@ class SkeletonPage(_SkeletonPage):
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
for k, v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
@ -73,7 +73,7 @@ class SkeletonPage(_SkeletonPage):
## CHEETAH: generated from #block writeHeadTag at line 22, col 1.
trans = KWS.get("trans")
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
if (not trans and not self._CHEETAH__isBuffering and not hasattr(self.transaction, '__call__')):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
@ -87,16 +87,16 @@ class SkeletonPage(_SkeletonPage):
## START - generated method body
write('<head>\n<title>')
_v = VFFSL(SL,"title",True) # '$title' on line 24, col 8
_v = VFFSL(SL, "title", True) # '$title' on line 24, col 8
if _v is not None: write(_filter(_v, rawExpr='$title')) # from line 24, col 8.
write('</title>\n')
_v = VFFSL(SL,"metaTags",True) # '$metaTags' on line 25, col 1
_v = VFFSL(SL, "metaTags", True) # '$metaTags' on line 25, col 1
if _v is not None: write(_filter(_v, rawExpr='$metaTags')) # from line 25, col 1.
write(' \n')
_v = VFFSL(SL,"stylesheetTags",True) # '$stylesheetTags' on line 26, col 1
_v = VFFSL(SL, "stylesheetTags", True) # '$stylesheetTags' on line 26, col 1
if _v is not None: write(_filter(_v, rawExpr='$stylesheetTags')) # from line 26, col 1.
write(' \n')
_v = VFFSL(SL,"javascriptTags",True) # '$javascriptTags' on line 27, col 1
_v = VFFSL(SL, "javascriptTags", True) # '$javascriptTags' on line 27, col 1
if _v is not None: write(_filter(_v, rawExpr='$javascriptTags')) # from line 27, col 1.
write('\n</head>\n')
@ -112,7 +112,7 @@ class SkeletonPage(_SkeletonPage):
## CHEETAH: generated from #block writeBody at line 36, col 1.
trans = KWS.get("trans")
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
if (not trans and not self._CHEETAH__isBuffering and not hasattr(self.transaction, '__call__')):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
@ -138,7 +138,7 @@ class SkeletonPage(_SkeletonPage):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
if (not trans and not self._CHEETAH__isBuffering and not hasattr(self.transaction, '__call__')):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
@ -172,29 +172,29 @@ class SkeletonPage(_SkeletonPage):
_orig_transheader = trans
trans = _cacheCollector_header = DummyTransaction()
write = _cacheCollector_header.response().write
_v = VFFSL(SL,"docType",True) # '$docType' on line 7, col 1
_v = VFFSL(SL, "docType", True) # '$docType' on line 7, col 1
if _v is not None: write(_filter(_v, rawExpr='$docType')) # from line 7, col 1.
write('\n')
_v = VFFSL(SL,"htmlTag",True) # '$htmlTag' on line 8, col 1
_v = VFFSL(SL, "htmlTag", True) # '$htmlTag' on line 8, col 1
if _v is not None: write(_filter(_v, rawExpr='$htmlTag')) # from line 8, col 1.
write('''
<!-- This document was autogenerated by Cheetah(http://CheetahTemplate.org).
Do not edit it directly!
Copyright ''')
_v = VFFSL(SL,"currentYr",True) # '$currentYr' on line 12, col 11
_v = VFFSL(SL, "currentYr", True) # '$currentYr' on line 12, col 11
if _v is not None: write(_filter(_v, rawExpr='$currentYr')) # from line 12, col 11.
write(' - ')
_v = VFFSL(SL,"siteCopyrightName",True) # '$siteCopyrightName' on line 12, col 24
_v = VFFSL(SL, "siteCopyrightName", True) # '$siteCopyrightName' on line 12, col 24
if _v is not None: write(_filter(_v, rawExpr='$siteCopyrightName')) # from line 12, col 24.
write(' - All Rights Reserved.\nFeel free to copy any javascript or html you like on this site,\nprovided you remove all links and/or references to ')
_v = VFFSL(SL,"siteDomainName",True) # '$siteDomainName' on line 14, col 52
_v = VFFSL(SL, "siteDomainName", True) # '$siteDomainName' on line 14, col 52
if _v is not None: write(_filter(_v, rawExpr='$siteDomainName')) # from line 14, col 52.
write('''
However, please do not copy any content or images without permission.
''')
_v = VFFSL(SL,"siteCredits",True) # '$siteCredits' on line 17, col 1
_v = VFFSL(SL, "siteCredits", True) # '$siteCredits' on line 17, col 1
if _v is not None: write(_filter(_v, rawExpr='$siteCredits')) # from line 17, col 1.
write('''
@ -215,7 +215,7 @@ However, please do not copy any content or images without permission.
## END CACHE REGION: header
write('\n')
_v = VFFSL(SL,"bodyTag",True) # '$bodyTag' on line 34, col 1
_v = VFFSL(SL, "bodyTag", True) # '$bodyTag' on line 34, col 1
if _v is not None: write(_filter(_v, rawExpr='$bodyTag')) # from line 34, col 1.
write('\n\n')
self.writeBody(trans=trans)

View File

@ -46,8 +46,8 @@ class _SkeletonPage(Template):
def __init__(self, *args, **KWs):
Template.__init__(self, *args, **KWs)
self._metaTags = {'HTTP-EQUIV':{'keywords':'Cheetah',
'Content-Type':'text/html; charset=iso-8859-1',
self._metaTags = {'HTTP-EQUIV':{'keywords': 'Cheetah',
'Content-Type': 'text/html; charset=iso-8859-1',
},
'NAME':{'generator':'Cheetah: The Python-Powered Template Engine'}
}
@ -85,7 +85,7 @@ class _SkeletonPage(Template):
stylesheetTagsTxt += '<style type="text/css"><!--\n'
for identifier in self._stylesheetsOrder:
if not self._stylesheets.has_key(identifier):
if identifier not in self._stylesheets:
warning = '# the identifier ' + identifier + \
'was in stylesheetsOrder, but not in stylesheets'
print(warning)
@ -117,7 +117,7 @@ class _SkeletonPage(Template):
javascriptTagsTxt = []
for key, details in self._javascriptTags.iteritems():
if not isinstance(details, (list, tuple)):
details = ['',details]
details = ['', details]
javascriptTagsTxt += ['<script language="JavaScript', str(details[0]),
'" type="text/javascript"><!--\n',
@ -126,7 +126,7 @@ class _SkeletonPage(Template):
for key, details in self._javascriptLibs.iteritems():
if not isinstance(details, (list, tuple)):
details = ['',details]
details = ['', details]
javascriptTagsTxt += ['<script language="JavaScript', str(details[0]),
'" type="text/javascript" src="',
@ -177,16 +177,16 @@ class _SkeletonPage(Template):
return ''.join(['<img src="', src, '" height="', str(height),
'" alt="', alt, '" border="', str(border), '" />'])
else:
return ''.join(['<img src="', src, '" alt="', alt, '" border="', str(border),'" />'])
return ''.join(['<img src="', src, '" alt="', alt, '" border="', str(border), '" />'])
def currentYr(self):
"""Return a string representing the current yr."""
return time.strftime("%Y",time.localtime(time.time()))
return time.strftime("%Y", time.localtime(time.time()))
def currentDate(self, formatString="%b %d, %Y"):
"""Return a string representing the current localtime."""
return time.strftime(formatString,time.localtime(time.time()))
return time.strftime(formatString, time.localtime(time.time()))
def spacer(self, width=1,height=1):
return '<img src="spacer.gif" width="%s" height="%s" alt="" />'% (str(width), str(height))
@ -195,19 +195,19 @@ class _SkeletonPage(Template):
"""returns a string containing an HTML <tag> """
tagTxt = ['<', tagName.lower()]
for name, val in attributes.items():
tagTxt += [' ', name.lower(), '="', str(val),'"']
tagTxt += [' ', name.lower(), '="', str(val), '"']
tagTxt.append('>')
return ''.join(tagTxt)
def formatMetaTags(self, metaTags):
"""format a dict of metaTag definitions into an HTML version"""
metaTagsTxt = []
if metaTags.has_key('HTTP-EQUIV'):
if 'HTTP-EQUIV' in metaTags:
for http_equiv, contents in metaTags['HTTP-EQUIV'].items():
metaTagsTxt += ['<meta http-equiv="', str(http_equiv), '" content="',
str(contents), '" />\n']
if metaTags.has_key('NAME'):
if 'NAME' in metaTags:
for name, contents in metaTags['NAME'].items():
metaTagsTxt += ['<meta name="', str(name), '" content="', str(contents),
'" />\n']

View File

@ -531,7 +531,7 @@ def listTests(cheetahWrapperFile):
"""
rx = re.compile( R'self\.go\("(.*?)"\)' )
f = open(cheetahWrapperFile)
while 1:
while True:
lin = f.readline()
if not lin:
break

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python
from __future__ import generators
import sys
import types
import os
@ -34,7 +34,7 @@ class DummyClass:
x = 'A string'
try:
for i in [1,2,3,4]:
for i in [1, 2, 3, 4]:
if x == 2:
pass
@ -53,52 +53,52 @@ def funcThatRaises():
testNamespace = {
'aStr':'blarg',
'anInt':1,
'aFloat':1.5,
'aDict': {'one':'item1',
'two':'item2',
'nestedDict':{'one':'nestedItem1',
'two':'nestedItem2',
'funcThatRaises':funcThatRaises,
'aStr': 'blarg',
'anInt': 1,
'aFloat': 1.5,
'aDict': {'one': 'item1',
'two': 'item2',
'nestedDict': {'one': 'nestedItem1',
'two': 'nestedItem2',
'funcThatRaises': funcThatRaises,
'aClass': DummyClass,
},
'nestedFunc':dummyFunc,
'nestedFunc': dummyFunc,
},
'aClass': DummyClass,
'aFunc': dummyFunc,
'anObj': DummyClass(),
'aMeth': DummyClass().meth1,
'none' : None,
'emptyString':'',
'funcThatRaises':funcThatRaises,
'none': None,
'emptyString': '',
'funcThatRaises': funcThatRaises,
}
autoCallResults = {'aFunc':'Scooby',
'aMeth':'doo',
autoCallResults = {'aFunc': 'Scooby',
'aMeth': 'doo',
}
results = testNamespace.copy()
results.update({'anObj.meth1':'doo',
'aDict.one':'item1',
'aDict.nestedDict':testNamespace['aDict']['nestedDict'],
'aDict.nestedDict.one':'nestedItem1',
'aDict.nestedDict.aClass':DummyClass,
'aDict.nestedFunc':'Scooby',
'aClass.classVar1':123,
'anObj.instanceVar1':123,
'anObj.meth3':'A string',
results.update({'anObj.meth1': 'doo',
'aDict.one': 'item1',
'aDict.nestedDict': testNamespace['aDict']['nestedDict'],
'aDict.nestedDict.one': 'nestedItem1',
'aDict.nestedDict.aClass': DummyClass,
'aDict.nestedFunc': 'Scooby',
'aClass.classVar1': 123,
'anObj.instanceVar1': 123,
'anObj.meth3': 'A string',
})
for k in testNamespace.keys():
# put them in the globals for the valueFromFrame tests
exec '%s = testNamespace[k]'%k
exec('%s = testNamespace[k]'%k)
##################################################
## TEST BASE CLASSES
class NameMapperTest(unittest.TestCase):
failureException = (NotFound,AssertionError)
failureException = (NotFound, AssertionError)
_testNamespace = testNamespace
_results = results
@ -117,7 +117,7 @@ class NameMapperTest(unittest.TestCase):
def check(self, name):
got = self.get(name)
if autoCallResults.has_key(name):
if name in autoCallResults:
expected = autoCallResults[name]
else:
expected = self._results[name]
@ -317,7 +317,7 @@ class VFN(NameMapperTest):
def test(self=self):
self.get('anObj.methX')
self.assertRaises(NotFound,test)
self.assertRaises(NotFound, test)
def test44(self):
"""NotFound test in a loop"""
@ -325,7 +325,7 @@ class VFN(NameMapperTest):
self.get('anObj.methX')
for i in range(10):
self.assertRaises(NotFound,test)
self.assertRaises(NotFound, test)
def test45(self):
"""Other exception from meth test"""
@ -340,7 +340,7 @@ class VFN(NameMapperTest):
self.get('anObj.meth2')
for i in range(10):
self.assertRaises(ValueError,test)
self.assertRaises(ValueError, test)
def test47(self):
"""None in dict lookup"""
@ -373,7 +373,7 @@ class VFN(NameMapperTest):
self.get('funcThatRaises')
for i in range(10):
self.assertRaises(ValueError,test)
self.assertRaises(ValueError, test)
def test53(self):
@ -389,7 +389,7 @@ class VFN(NameMapperTest):
self.get('aDict.nestedDict.funcThatRaises')
for i in range(10):
self.assertRaises(ValueError,test)
self.assertRaises(ValueError, test)
def test55(self):
"""aDict.nestedDict.aClass in dict lookup"""
@ -428,10 +428,10 @@ class VFS(VFN):
if lng == 1:
return [self.namespace()]
elif lng == 2:
return [self.namespace(),{'dummy':1234}]
return [self.namespace(), {'dummy':1234}]
elif lng == 3:
# a tuple for kicks
return ({'dummy':1234}, self.namespace(),{'dummy':1234})
return ({'dummy':1234}, self.namespace(), {'dummy':1234})
elif lng == 4:
# a generator for more kicks
return self.searchListGenerator()
@ -439,7 +439,7 @@ class VFS(VFN):
def searchListGenerator(self):
class Test:
pass
for i in [Test(),{'dummy':1234}, self.namespace(),{'dummy':1234}]:
for i in [Test(), {'dummy':1234}, self.namespace(), {'dummy':1234}]:
yield i
def get(self, name, autocall=True):

View File

@ -78,7 +78,7 @@ class DynamicTemplatePerformanceTest(unittest.TestCase):
#pass
#end def
'''
for i in xrange(self.loops):
for i in range(self.loops):
klass = Cheetah.Template.Template.compile(template)
assert klass
test_BasicDynamic = perftest(1200)(test_BasicDynamic)
@ -91,7 +91,7 @@ class PerformanceTest(unittest.TestCase):
def runTest(self):
self.prof = hotshot.Profile('%s.prof' % self.__class__.__name__)
self.prof.start()
for i in xrange(self.iterations):
for i in range(self.iterations):
if hasattr(self, 'performanceSample'):
self.display = True
self.performanceSample()
@ -130,7 +130,7 @@ class BunchOfWriteCalls(PerformanceTest):
template = '''
#import sys
#import os
#for i in xrange(1000)
#for i in range(1000)
$i
#end for
'''
@ -210,7 +210,7 @@ class LongCompileTest(PerformanceTest):
<body>
$header()
#for $i in $xrange(10)
#for $i in $range(10)
This is just some stupid page!
<br/>
#end for

View File

@ -67,37 +67,37 @@ def dummyFunc(arg="Scooby"):
return arg
defaultTestNameSpace = {
'aStr':'blarg',
'anInt':1,
'aFloat':1.5,
'aList': ['item0','item1','item2'],
'aDict': {'one':'item1',
'two':'item2',
'nestedDict':{1:'nestedItem1',
'aStr': 'blarg',
'anInt': 1,
'aFloat': 1.5,
'aList': ['item0', 'item1', 'item2'],
'aDict': {'one': 'item1',
'two': 'item2',
'nestedDict': {1:'nestedItem1',
'two':'nestedItem2'
},
'nestedFunc':dummyFunc,
'nestedFunc': dummyFunc,
},
'aFunc': dummyFunc,
'anObj': DummyClass(),
'aMeth': DummyClass().meth1,
'aStrToBeIncluded': "$aStr $anInt",
'none' : None,
'emptyString':'',
'numOne':1,
'numTwo':2,
'zero':0,
'none': None,
'emptyString': '',
'numOne': 1,
'numTwo': 2,
'zero': 0,
'tenDigits': 1234567890,
'webSafeTest': 'abc <=> &',
'strip1': ' \t strippable whitespace \t\t \n',
'strip2': ' \t strippable whitespace \t\t ',
'strip3': ' \t strippable whitespace \t\t\n1 2 3\n',
'blockToBeParsed':"""$numOne $numTwo""",
'includeBlock2':"""$numOne $numTwo $aSetVar""",
'blockToBeParsed': """$numOne $numTwo""",
'includeBlock2': """$numOne $numTwo $aSetVar""",
'includeFileName':'parseTest.txt',
'listOfLambdas':[lambda x: x, lambda x: x, lambda x: x,],
'includeFileName': 'parseTest.txt',
'listOfLambdas': [lambda x: x, lambda x: x, lambda x: x,],
'list': [
{'index': 0, 'numOne': 1, 'numTwo': 2},
{'index': 1, 'numOne': 1, 'numTwo': 2},
@ -105,7 +105,7 @@ defaultTestNameSpace = {
'nameList': [('john', 'doe'), ('jane', 'smith')],
'letterList': ['a', 'b', 'c'],
'_': lambda x: 'Translated: ' + x,
'unicodeData':u'aoeu12345\u1234',
'unicodeData': u'aoeu12345\u1234',
}
@ -185,9 +185,9 @@ Template output mismatch:
if self._debugEOLReplacement and self._EOLreplacement:
EOLrepl = self._EOLreplacement
marker = '*EOL*'
return self.report % {'template': self._input.replace(EOLrepl,marker),
'expected': expectedOutput.replace(EOLrepl,marker),
'actual': output.replace(EOLrepl,marker),
return self.report % {'template': self._input.replace(EOLrepl, marker),
'expected': expectedOutput.replace(EOLrepl, marker),
'actual': output.replace(EOLrepl, marker),
'end': '(end)'}
else:
return self.report % {'template': self._input,
@ -237,7 +237,7 @@ class Backslashes(OutputTest):
convertEOLs = False
def setUp(self):
fp = open('backslashes.txt','w')
fp = open('backslashes.txt', 'w')
fp.write(r'\ #LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')
fp.flush()
fp.close
@ -620,7 +620,7 @@ class Placeholders(OutputTest):
tmpl = tmpl.subclass('#for name in $names: $*1*(name) ')
assert str(tmpl({'names':names}))=='You '*len(names)
if versionTuple > (2,2):
if versionTuple > (2, 2):
tmpl = tmpl.subclass('#for name in $names: $*1*(name) ')
assert str(tmpl(names=names))=='You '*len(names)
@ -1477,7 +1477,7 @@ class YieldDirective(OutputTest):
)
for src in (src1,src2,src3):
for src in (src1, src2, src3):
klass = Template.compile(src, keepRefToGeneratedCode=True)
#print klass._CHEETAH_generatedModuleCode
iter = klass().respond()
@ -1487,7 +1487,7 @@ class YieldDirective(OutputTest):
# @@TR: need to expand this to cover error conditions etc.
if versionTuple < (2,3):
if versionTuple < (2, 3):
del YieldDirective
class ForDirective(OutputTest):
@ -1589,7 +1589,7 @@ class ForDirective(OutputTest):
self.verify("#for $i in range(5): \n$i\n#end for",
"0\n1\n2\n3\n4\n")
if versionTuple < (2,3):
if versionTuple < (2, 3):
del ForDirective.test12
class RepeatDirective(OutputTest):
@ -1826,7 +1826,7 @@ class DecoratorDirective(OutputTest):
"$testMeth",
"1234\n")
if versionTuple < (2,4):
if versionTuple < (2, 4):
del DecoratorDirective
class BlockDirective(OutputTest):
@ -1941,7 +1941,7 @@ inner
class IncludeDirective(OutputTest):
def setUp(self):
fp = open('parseTest.txt','w')
fp = open('parseTest.txt', 'w')
fp.write("$numOne $numTwo")
fp.flush()
fp.close
@ -3192,7 +3192,7 @@ public class X
##################################################
## CREATE CONVERTED EOL VERSIONS OF THE TEST CASES
if OutputTest._useNewStyleCompilation and versionTuple >= (2,3):
if OutputTest._useNewStyleCompilation and versionTuple >= (2, 3):
extraCompileKwArgsForDiffBaseclass = {'baseclass':dict}
else:
extraCompileKwArgsForDiffBaseclass = {'baseclass':object}
@ -3202,16 +3202,16 @@ def install_eols():
klasses = [v for v in globals().values() if isinstance(v, type) and issubclass(v, unittest.TestCase)]
for klass in klasses:
name = klass.__name__
if hasattr(klass,'convertEOLs') and klass.convertEOLs:
if hasattr(klass, 'convertEOLs') and klass.convertEOLs:
win32Src = r"class %(name)s_Win32EOL(%(name)s): _EOLreplacement = '\r\n'"%locals()
macSrc = r"class %(name)s_MacEOL(%(name)s): _EOLreplacement = '\r'"%locals()
exec win32Src in globals()
exec macSrc in globals()
exec(win32Src, globals())
exec(macSrc, globals())
if versionTuple >= (2,3):
if versionTuple >= (2, 3):
src = r"class %(name)s_DiffBaseClass(%(name)s): "%locals()
src += " _extraCompileKwArgs = extraCompileKwArgsForDiffBaseclass"
exec src in globals()
exec(src, globals())
del name
del klass

View File

@ -44,7 +44,7 @@ class ClassMethods_compile(TemplateTest):
assert str(t)=='1234'
def test_moduleFileCaching(self):
if versionTuple < (2,3):
if versionTuple < (2, 3):
return
tmpDir = tempfile.mkdtemp()
try:
@ -220,9 +220,9 @@ class Preprocessors(TemplateTest):
class TemplateSubclass(Template):
pass
compilerSettings = {'cheetahVarStartToken':'@',
'directiveStartToken':'%',
'commentStartToken':'%%',
compilerSettings = {'cheetahVarStartToken': '@',
'directiveStartToken': '%',
'commentStartToken': '%%',
}
for arg in ['@ %',

View File

@ -68,7 +68,7 @@ class CGITemplate(Template):
def isCgi(self):
"""Is this a CGI script?
"""
env = os.environ.has_key('REQUEST_METHOD')
env = 'REQUEST_METHOD' in os.environ
wk = self._CHEETAH__isControlledByWebKit
return env and not wk

View File

@ -13,6 +13,13 @@ next.query.
How about Report: .page(), .all(), .summary()? Or PageBreaker.
"""
import operator
try:
from functools import reduce
except ImportError:
# If functools doesn't exist, we must be on an old
# enough version that has reduce() in builtins
pass
try:
from Cheetah.NameMapper import valueForKey as lookup_func
except ImportError:
@ -86,8 +93,7 @@ def mean(lis):
return total / lis_len
def median(lis):
lis = lis[:]
lis.sort()
lis = sorted(lis[:])
return lis[int(len(lis)/2)]
@ -164,7 +170,7 @@ class ValuesGetterMixin:
else:
ret = self._origList
if criteria:
ret = filter(criteria, ret)
ret = list(filter(criteria, ret))
return ret
@ -266,7 +272,7 @@ class RecordStats(IndexFormats, ValuesGetterMixin):
def _prevNextHelper(self, start,end,size,orphan,sequence):
def _prevNextHelper(self, start, end, size, orphan, sequence):
"""Copied from Zope's DT_InSV.py's "opt" function.
"""
if size < 1:
@ -299,7 +305,7 @@ class RecordStats(IndexFormats, ValuesGetterMixin):
try: sequence[end+orphan-1]
except: end=len(sequence)
# if l - end < orphan: end=l
return start,end,size
return start, end, size

View File

@ -139,7 +139,6 @@ class Hierarchy:
if self._inContents(item):
return True
return False
##################################################
## from the command line

View File

@ -11,7 +11,7 @@ def _recompile_template(package, basename, tfile, classname):
code = str(c)
mod = imp.new_module(classname)
ns = dict()
exec code in ns
exec(code, ns)
tempclass = ns.get("GenTemplate",
ns.get('DynamicallyCompiledCheetahTemplate'))
assert tempclass
@ -38,7 +38,7 @@ class TurboCheetah:
Template files must end in ".tmpl" and be in legitimate packages.
"""
given = len(filter(None, (template, template_string, template_file)))
given = len([_f for _f in (template, template_string, template_file) if _f])
if given > 1:
raise TypeError(
"You may give only one of template, template_string, and "
@ -63,14 +63,14 @@ class TurboCheetah:
package = classname[0:divider]
basename = classname[divider+1:]
else:
raise ValueError, "All templates must be in a package"
raise ValueError("All templates must be in a package")
if not self.options.get("cheetah.precompiled", False):
tfile = pkg_resources.resource_filename(package,
"%s.%s" %
(basename,
self.extension))
if ct.has_key(classname):
if classname in ct:
mtime = os.stat(tfile).st_mtime
if ct[classname] != mtime:
ct[classname] = mtime

View File

@ -128,7 +128,7 @@ class Client:
serverData = {}
data.append(( name, serverData ))
readline = s.readline
while 1:
while True:
line = readline()
if not line or line.strip() == 'END': break
stats = line.split(' ', 2)
@ -148,7 +148,7 @@ class Client:
sys.stderr.write("MemCached: %s\n" % str)
def _statlog(self, func):
if not self.stats.has_key(func):
if func not in self.stats:
self.stats[func] = 1
else:
self.stats[func] += 1
@ -376,7 +376,7 @@ class Client:
server, key = self._get_server(key)
if not server:
continue
if not server_keys.has_key(server):
if server not in server_keys:
server_keys[server] = []
server_keys[server].append(key)
@ -515,7 +515,7 @@ class _Host:
def readline(self):
buffers = ''
recv = self.socket.recv
while 1:
while True:
data = recv(1)
if not data:
self.mark_dead('Connection closed while reading from %s'

View File

@ -120,7 +120,7 @@ much as possible.
"""
from __future__ import division
try:
import itimer

View File

@ -2,11 +2,11 @@ Version = '2.4.0'
VersionTuple = (2, 4, 0, 'final', 0)
MinCompatibleVersion = '2.0rc6'
MinCompatibleVersionTuple = (2,0,0,'candidate',6)
MinCompatibleVersionTuple = (2, 0, 0, 'candidate', 6)
####
def convertVersionStringToTuple(s):
versionNum = [0,0,0]
versionNum = [0, 0, 0]
releaseType = 'final'
releaseTypeSubNum = 0
if s.find('a')!=-1:
@ -27,7 +27,7 @@ def convertVersionStringToTuple(s):
versionNum += [0]
releaseTypeSubNum = int(releaseTypeSubNum)
return tuple(versionNum+[releaseType,releaseTypeSubNum])
return tuple(versionNum+[releaseType, releaseTypeSubNum])
if __name__ == '__main__':