Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!news2.euro.net!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; '2.7': 0.04; 'assign': 0.04; 'exec': 0.07; '""")': 0.09; 'globals': 0.09; 'received:188.220': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:80.91.229.12': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'received:lo.gmane.org': 0.09; 'def': 0.15; 'src,': 0.16; 'test()': 0.16; 'test():': 0.16; 'this:': 0.16; 'string,': 0.18; 'seems': 0.20; 'wrote': 0.20; 'versions': 0.23; 'produces': 0.23; 'function': 0.27; 'earlier': 0.32; 'does': 0.32; 'it.': 0.33; 'to:addr:python-list': 0.33; '...': 0.34; 'header:User-Agent:1': 0.34; 'header:X-Complaints-To:1': 0.35; 'received:org': 0.38; 'subject:: ': 0.39; 'manually': 0.39; 'user': 0.39; 'to:addr:python.org': 0.39; 'subject:from': 0.40; 'double': 0.61; 'it)': 0.67; 'received:188': 0.68; 'received:bethere.co.uk': 0.84; 'subject:value': 0.84; 'subject:better': 0.93 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Rob Williscroft Subject: Re: Returning a value from exec or a better solution Date: Mon, 29 Aug 2011 17:30:53 +0000 (UTC) References: X-Gmane-NNTP-Posting-Host: 188-220-43-229.zone11.bethere.co.uk User-Agent: Xnews/5.04.25 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 34 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1314639069 news.xs4all.nl 2466 [2001:888:2000:d::a6]:49310 X-Complaints-To: abuse@xs4all.nl Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:12408 Jack Trades wrote in news:CAG5udOg=GtFGPmTB=1OJNvNRPdYUcxDoKN1WJQMOMv9gx0+fZA@mail.gmail.com in gmane.comp.python.general: > ... I wanted to allow the user to manually return the > function from the string, like this: > > a = exec(""" > def double(x): > return x * 2 > double > """) > > However it seems that exec does not return a value as it produces a > SyntaxError whenever I try to assign it. def test(): src = ( "def double(x):" " return x * 2" ) globals = {} exec( src, globals ) return globals[ "double" ] print( test() ) The a bove works on 2.7 (I tested it) on earlier versions you may need to use: exec src in globals Rob.