with keyword problem
Status: Alpha
Brought to you by:
grahamcarlyle
In Python 2.6 keyword 'with' became a reserved keyword!
Here is a link to the documentation: http://docs.python.org/reference/compound_stmts.html#with
The problem is that there is a method in InvocationMockerBuilder class with the same name. So, there in no chance to execute any script using pmock under Pyhton 2.6 as yet.
Since the homepage for this project indicates that it's abandoned, I thought I'd add my solution to the problem. I decided to use an import hook that dynamically changes the "with" -> "with_". It's not terribly elegant, but it prevents me from having to maintain a fork of the project locally:
Just add the code below, and make sure it's imported before you ever import pmock:
=================
class PmockImportHook(object):
'''An import hook that provides custom loading of the pmock library.
Pmock is incompatible with Python 2.6 because it attempts to define
a method named "with" which has become a reserved word. This hook
replaces that function with the name "with_" dynamically while
importing pmock.
See: http://www.python.org/dev/peps/pep-0302/
'''
def __init__(self, pathname):
if 'pmock' not in pathname or 'Updates' in pathname:
raise ImportError
def find_module(self, fullname):
if fullname == 'pmock':
return self
def load_module(self, fullname):
print
print '%s: Performing custom import for: %s' % (self.__class__.__name__, fullname)
code = self._get_code(fullname)
module = sys.modules.setdefault(fullname, imp.new_module(fullname))
module.__file__ = "<%s>" % self.__class__.__name__
module.__loader__ = self
exec code in module.__dict__
return module
def _get_code(self, fullname):
sourceFile = None
try:
sourceFile, sourcePath, description = imp.find_module(fullname)
print ' sourcepath: %s' % sourcePath
source = sourceFile.read()
lines = source.splitlines()
for index, line in enumerate(lines):
# Find the offending line and replace it
if 'with(' in line:
newLine = line.replace('with(', 'with_(')
print ' Replacing line %s: ' % index
print ' Original: %s' % line
print ' Replaced: %s' % newLine
lines[index] = newLine
return '\n'.join(lines)
finally:
if sourceFile:
sourceFile.close()
sys.path_hooks.append(PmockImportHook)
sys.path_importer_cache.clear()
=================
Crap -- sorry about the formatting...
You should be able to fix it by hand, just make sure that the final couple of lines:
sys.path_hooks.append(PmockImportHook)
sys.path_importer_cache.clear()
are not included in the PmockImportHook class (they're executed globally, after PmockImportHook is defined).
Thanks, chphilli
I patched pmock to work with Python 2.6 and put the code on github:
http://github.com/gma/pmock