Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32483

Re: exec with partial globals

Date 2012-10-30 08:33 -0400
From Dave Angel <d@davea.name>
Subject Re: exec with partial globals
References <af9tq3FnmkaU1@mid.dfncis.de>
Newsgroups comp.lang.python
Message-ID <mailman.3087.1351600438.27098.python-list@python.org> (permalink)

Show all headers | View raw


On 10/30/2012 08:00 AM, Helmut Jarausch wrote:
> Hi,
>
> I'd like to give the user the ability to enter code which may only rebind
> a given set of names but not all ones.
> This does NOT work
> A=1
> B=2
> Code=compile('A=7','','exec')
> exec(Code,{'A':0})
> print("I've got A={}".format(A)) # prints 1
>
>
> How can 'filter' the gobal namespace such that modifying 'A' is allowed
> but any attempt to modify 'B' should give an exception.
>
>
> Many thanks for a hint,
> Helmut.

A=1
B=2
Code=compile('A=7','','exec')
vars = {'A':A}
exec(Code, vars)
A = vars["A"]
print("I've got A={}".format(A)) # prints 1

That now prints "I've got A=7"

More generally, you could write a loop, copying globals into vars, and
another one, copying them back.

No idea what you're really after;  this is one of the more dangerous
things to try.

Although you can constrain the globals seen by the code, that code can
still use builtins, do imports, delete files, etc.

Further, if your user is clever enough, he can do:

Code=compile('A=7; print("howdy"); import __main__;
__main__.B=42','','exec')

What are you really trying to permit him to do?  Initialize some
variables for you?  How about an .ini file ?




-- 

DaveA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

exec with partial globals Helmut Jarausch <jarausch@igpm.rwth-aachen.de> - 2012-10-30 12:00 +0000
  Re: exec with partial globals Chris Angelico <rosuav@gmail.com> - 2012-10-30 23:28 +1100
  Re: exec with partial globals Dave Angel <d@davea.name> - 2012-10-30 08:33 -0400
    Re: exec with partial globals Helmut Jarausch <jarausch@igpm.rwth-aachen.de> - 2012-10-30 12:57 +0000
      Re: exec with partial globals Chris Angelico <rosuav@gmail.com> - 2012-10-31 00:18 +1100
      Re: exec with partial globals Dave Angel <d@davea.name> - 2012-10-30 09:39 -0400

csiph-web