469,282 Members | 1,921 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,282 developers. It's quick & easy.

How can I exec() in global?

Hi.

Is it possible to exec() from within a function so the exec'd
code affects global?

For example

def foo():
exec ('X=[1,2,3]')

And I'd like 'X' to be a global variable.
Thanks,

Gerald
Jul 18 '05 #1
6 5037
Jerald wrote:
Is it possible to exec() from within a function so the exec'd
code affects global?

For example

def foo():
exec ('X=[1,2,3]')

And I'd like 'X' to be a global variable.

x Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined def foo(): .... exec "x = [1, 2, 3]" in globals()
.... foo()
x

[1, 2, 3]

Peter

Jul 18 '05 #2
You can do exec(some_code, globals(), globals()) to execute some_code as
if it were executed at module scope. I can't really think of a reason
off hand why you would want to do this, but I assume you have your
reasons.

On Sat, Sep 11, 2004 at 09:17:02PM -0700, Jerald wrote:
Hi.

Is it possible to exec() from within a function so the exec'd
code affects global?

For example

def foo():
exec ('X=[1,2,3]')

And I'd like 'X' to be a global variable.
Thanks,

Gerald

Jul 18 '05 #3
Hi too !

You can, also, to do :

def foo():
exec ('''global X
X=[1,2,3]''')

@-salutations
--
Michel Claveau

Jul 18 '05 #4
Hi !
I have one sample reason (only me ?) : i had make a COM-server in Python ;
and i send, from other applis, some Python's scripts, by a string, like
parameters. My COM-server can to execute this scripts.
*sorry for my bad english*
@-salutations
--
Michel Claveau

Jul 18 '05 #5
Michel Claveau - abstraction méta-galactique non triviale en fuite
perpétuelle. wrote:

I have one sample reason (only me ?) : i had make a COM-server in Python ;
and i send, from other applis, some Python's scripts, by a string, like
parameters. My COM-server can to execute this scripts.


Similar reason here.

def mydef(X):
exec (X)

And

mydef("""
def g():
print 'Hi'
""")
cheers

Gerald
Jul 18 '05 #6
re-Hi !

http://ponx.org (IE only, with scripts autorized)
Jul 18 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Jimmy Jim | last post: by
2 posts views Thread by Jonathan | last post: by
5 posts views Thread by Nick Jacobson | last post: by
3 posts views Thread by kepes.krisztian | last post: by
1 post views Thread by Andr? Roberge | last post: by
2 posts views Thread by N. Pourcelot | last post: by
10 posts views Thread by Antoon Pardon | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.