How can I exec() in global?

P

Peter Otten

Jerald said:
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.
Traceback (most recent call last):
.... exec "x = [1, 2, 3]" in globals()
....[1, 2, 3]

Peter
 
P

Phil Frost

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.
 
M

Michel Claveau - abstraction méta-galactique non t

Hi too !



You can, also, to do :

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



@-salutations
 
M

Michel Claveau - abstraction méta-galactique non t

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
 
J

Jerald

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
 
J

Jerald

Michel Claveau - abstraction méta-galactique non triviale en fuite
perpétuelle. said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,675
Latest member
RollandKna

Latest Threads

Top