Importación de Python que causa un error de sintaxis

I'm an old-fashioned Pascal programmer, new to OOP and Python, so please bear with me...I've got a book on Python and I've searched here first (although lots of similar threads - not checked every one)...

I'm trying to write a program to include existing modules written by others in my company. According to my Python book, I should be able to import whole modules or just specific classes. The book says that when 'import' is used, it actually runs the specified code (not like the INHERIT I'm used to in Pascal).

I have this structure in the module,, I want to use:

from x.y.z import stuff

class c1(superclass):
    def func1(self):
    def func2(self, db):
        with self.db as handler:

and I've got a basic script,, that does just this:

from mod import c1

print "Hello"

when I execute 'python', I get the error message:

'with self.db as handler' - invalid syntax

I think I'm missing something fundamental here, so any help much appreciated.

preguntado el 03 de mayo de 12 a las 15:05

Sospecho que tu self.db no implementa el protocolo de administrador de contexto, o no? -

Could also be that this is too old a Python to have that syntax -- Python 2.4 still lives in production some places. Which version is this? -

Your error suggests that you are putting the with statement in quotes, is that correct? What version of Python are you using? You should also update the question with the entire contents of -

@TimPietzcker That wouldn't cause a syntax error, and wouldn't (couldn't) be checked at import time. -

3 Respuestas

You have modified the error message, but I assume it looks like

  File "", line 8
    with self.db as handler:
SyntaxError: invalid syntax

This means that your Python version is too old to know the with ambiental. Update to an implementation that supports python 2.6+.

In Python 2.5, you can also add a __future__ declaración en la cima de, Así:

from __future__ import with_statement

contestado el 03 de mayo de 12 a las 15:05

Yes, that is what my error looks like. Hmm, I've been given an environment to use and I have no control over installing versions - would seem strange to have been given something out-of-date but I'll look into it...many thanks... - nelmo

In Python 2.5 the with statement is not available by default. But it is there! :-) Try adding

from __future__ import with_statement

to your or use Python 2.6+.

contestado el 03 de mayo de 12 a las 15:05

Newbie question - how do I tell what version I've got? (I'm on a Linux server) - nelmo

Given what that line looks like and the error being a syntax one, I'd look at the line before it and look for unmatched braces or quotes.

contestado el 03 de mayo de 12 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.