简体   繁体   中英

exec: SyntaxError: 'return' outside function

I'm storing code snippets inside the Postgres DB. When I need the code, I find it inside the DB and use exec() function. The code snippet is a body of extract function.

Unfortunately it returns SyntaxError: 'return' outside function

Method

def extract(self,response):
    exec(self.custom_code)

Code snippet (repr(code_snippet))

u"return response.xpath('/text()')"

I suppose that it should behave like this:

def extract(self,response):
    return response.xpath('/text()')

What I should do? This is just one line snippet and I need to execute multiline snippets.

EDIT:

I'm using Django with PostgreSQL and I realised that it strips spaces at the beginning of the line - indentation. I don't know if it has to do something with the problem.

EDIT2:

Tried eval instead of exec. Now it raises:

  File "/home/milano/PycharmProjects/Stilio_project/stilio/engine/models.py", line 107, in extract
    eval(self.custom_code)
  File "<string>", line 1
    return response.xpath('/text()')
         ^
SyntaxError: invalid syntax

Per the exec docs :

Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec statement.

So exec is explicitly off-limits. And that wording is global, not specific to exec ; on checking, while eval using code compile -ed in 'single' mode has the same error; you can't dynamically insert return statements like this.

If you absolutely must allow executing arbitrary code, I strongly recommend limiting it to expressions, not statements, and implicitly returning the result of said expressions. So instead of storing u"return response.xpath('/text()')" , you'd store u"response.xpath('/text()')" , and your code that performs dynamic invocation would change to:

def extract(self,response):
    return eval(self.custom_code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM