Execute script from string with accessing the variables?
up vote
0
down vote
favorite
I have a python script as a string, as example:
exec("sent = {'test': 1}")
global sent
print(sent)
I executed it using exec function, then I accessed the variable using global
python command. This way works without problem without using classes, but when I have the same code in a class, like:
class example:
def fun1(self):
exec("sent = {'test': 1}")
global sent
print(sent)
v = example()
print(v.fun1())
I get the following error:
NameError: name 'sent' is not defined
python python-3.x global-variables exec
add a comment |
up vote
0
down vote
favorite
I have a python script as a string, as example:
exec("sent = {'test': 1}")
global sent
print(sent)
I executed it using exec function, then I accessed the variable using global
python command. This way works without problem without using classes, but when I have the same code in a class, like:
class example:
def fun1(self):
exec("sent = {'test': 1}")
global sent
print(sent)
v = example()
print(v.fun1())
I get the following error:
NameError: name 'sent' is not defined
python python-3.x global-variables exec
Try: exec("global sent;sent = {}") . But avoid using global variables if you can.
– kantal
Nov 19 at 19:52
I can't add "global" to the string, because it's too long
– Ghanem
Nov 19 at 19:56
Ghanem: What do you mean it's too long? Strings can be almost any length in Python.
– martineau
Nov 20 at 0:40
It's a dataset, someone build it in a code format .. "dummy way"
– Ghanem
Nov 20 at 9:26
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I have a python script as a string, as example:
exec("sent = {'test': 1}")
global sent
print(sent)
I executed it using exec function, then I accessed the variable using global
python command. This way works without problem without using classes, but when I have the same code in a class, like:
class example:
def fun1(self):
exec("sent = {'test': 1}")
global sent
print(sent)
v = example()
print(v.fun1())
I get the following error:
NameError: name 'sent' is not defined
python python-3.x global-variables exec
I have a python script as a string, as example:
exec("sent = {'test': 1}")
global sent
print(sent)
I executed it using exec function, then I accessed the variable using global
python command. This way works without problem without using classes, but when I have the same code in a class, like:
class example:
def fun1(self):
exec("sent = {'test': 1}")
global sent
print(sent)
v = example()
print(v.fun1())
I get the following error:
NameError: name 'sent' is not defined
python python-3.x global-variables exec
python python-3.x global-variables exec
edited Nov 19 at 20:06
asked Nov 19 at 19:18
Ghanem
8542926
8542926
Try: exec("global sent;sent = {}") . But avoid using global variables if you can.
– kantal
Nov 19 at 19:52
I can't add "global" to the string, because it's too long
– Ghanem
Nov 19 at 19:56
Ghanem: What do you mean it's too long? Strings can be almost any length in Python.
– martineau
Nov 20 at 0:40
It's a dataset, someone build it in a code format .. "dummy way"
– Ghanem
Nov 20 at 9:26
add a comment |
Try: exec("global sent;sent = {}") . But avoid using global variables if you can.
– kantal
Nov 19 at 19:52
I can't add "global" to the string, because it's too long
– Ghanem
Nov 19 at 19:56
Ghanem: What do you mean it's too long? Strings can be almost any length in Python.
– martineau
Nov 20 at 0:40
It's a dataset, someone build it in a code format .. "dummy way"
– Ghanem
Nov 20 at 9:26
Try: exec("global sent;sent = {}") . But avoid using global variables if you can.
– kantal
Nov 19 at 19:52
Try: exec("global sent;sent = {}") . But avoid using global variables if you can.
– kantal
Nov 19 at 19:52
I can't add "global" to the string, because it's too long
– Ghanem
Nov 19 at 19:56
I can't add "global" to the string, because it's too long
– Ghanem
Nov 19 at 19:56
Ghanem: What do you mean it's too long? Strings can be almost any length in Python.
– martineau
Nov 20 at 0:40
Ghanem: What do you mean it's too long? Strings can be almost any length in Python.
– martineau
Nov 20 at 0:40
It's a dataset, someone build it in a code format .. "dummy way"
– Ghanem
Nov 20 at 9:26
It's a dataset, someone build it in a code format .. "dummy way"
– Ghanem
Nov 20 at 9:26
add a comment |
2 Answers
2
active
oldest
votes
up vote
1
down vote
accepted
You are not passing the global dictionary to modify. Try:
exec("sent = {}",globals())
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
add a comment |
up vote
1
down vote
You really should avoid using global variables. Regardless, here's how to do it:
class example:
def fun1(self):
# globals sent # Not needed in this special case.
exec("sent = {}", globals())
print('in fun1, "sent" is now', sent )
v = example()
print(v.fun1()) # Result will be None because fun1() doesn't return anything.
print('after call to fun1(), global "sent" is', sent)
Output:
in fun1, "sent" is now {}
None
after call to fun1(), global "sent" is {}
A global
declaration only does something inside a function or class method and even then is only needed when the global variable's value is going to be set to something.
However, as a special case, one isn't really needed here in the fun1()
method because it explicitly passes globals()
(but not a separate locals dict) when it calls exec()
. It might be a good idea to put one in anyway to make it more clear what's going on.
Using exec()
this way is explained in its documentation which says:
If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.
(emphasis mine)
Here's a way to avoid referencing a global variable at all in the method:
class example:
def fun1(self):
namespace = {}
exec("sent = {}", namespace)
sent = namespace['sent'] # Retrieve result.
print('in fun1, "sent" is now', sent )
return sent
v = example()
sent = v.fun1()
print('after calling fun1(), "sent" got set to', sent)
Output:
in fun1, "sent" is now {}
after calling fun1(), "sent" got set to {}
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is byreturn
ing them from the function/method. i.e.sent = v1.fun1()
(assuming you also put areturn sent
statement at the end of the method).
– martineau
Nov 19 at 21:49
add a comment |
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
accepted
You are not passing the global dictionary to modify. Try:
exec("sent = {}",globals())
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
add a comment |
up vote
1
down vote
accepted
You are not passing the global dictionary to modify. Try:
exec("sent = {}",globals())
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
add a comment |
up vote
1
down vote
accepted
up vote
1
down vote
accepted
You are not passing the global dictionary to modify. Try:
exec("sent = {}",globals())
You are not passing the global dictionary to modify. Try:
exec("sent = {}",globals())
answered Nov 19 at 20:03
John M I Davis
393
393
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
add a comment |
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
to make the question clear, I append a value to the "sent" variable
– Ghanem
Nov 19 at 20:07
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
The original question was trying to initialize 'sent' to an empty array. This does that. you may also set 'send' to a given dictionary, as in the modified question by: exec("sent = {'test': 1}",globals()) or modify a dictionary that was previously defined as global: exec(" my_global_dictionary['new_key'] = 'new_value'", global()) but adding the second argument, a reference to the global dictionary is crucial. If you do not add this exec creates a global dictionary = {} which is discarded after the function is called.
– John M I Davis
Nov 19 at 22:52
add a comment |
up vote
1
down vote
You really should avoid using global variables. Regardless, here's how to do it:
class example:
def fun1(self):
# globals sent # Not needed in this special case.
exec("sent = {}", globals())
print('in fun1, "sent" is now', sent )
v = example()
print(v.fun1()) # Result will be None because fun1() doesn't return anything.
print('after call to fun1(), global "sent" is', sent)
Output:
in fun1, "sent" is now {}
None
after call to fun1(), global "sent" is {}
A global
declaration only does something inside a function or class method and even then is only needed when the global variable's value is going to be set to something.
However, as a special case, one isn't really needed here in the fun1()
method because it explicitly passes globals()
(but not a separate locals dict) when it calls exec()
. It might be a good idea to put one in anyway to make it more clear what's going on.
Using exec()
this way is explained in its documentation which says:
If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.
(emphasis mine)
Here's a way to avoid referencing a global variable at all in the method:
class example:
def fun1(self):
namespace = {}
exec("sent = {}", namespace)
sent = namespace['sent'] # Retrieve result.
print('in fun1, "sent" is now', sent )
return sent
v = example()
sent = v.fun1()
print('after calling fun1(), "sent" got set to', sent)
Output:
in fun1, "sent" is now {}
after calling fun1(), "sent" got set to {}
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is byreturn
ing them from the function/method. i.e.sent = v1.fun1()
(assuming you also put areturn sent
statement at the end of the method).
– martineau
Nov 19 at 21:49
add a comment |
up vote
1
down vote
You really should avoid using global variables. Regardless, here's how to do it:
class example:
def fun1(self):
# globals sent # Not needed in this special case.
exec("sent = {}", globals())
print('in fun1, "sent" is now', sent )
v = example()
print(v.fun1()) # Result will be None because fun1() doesn't return anything.
print('after call to fun1(), global "sent" is', sent)
Output:
in fun1, "sent" is now {}
None
after call to fun1(), global "sent" is {}
A global
declaration only does something inside a function or class method and even then is only needed when the global variable's value is going to be set to something.
However, as a special case, one isn't really needed here in the fun1()
method because it explicitly passes globals()
(but not a separate locals dict) when it calls exec()
. It might be a good idea to put one in anyway to make it more clear what's going on.
Using exec()
this way is explained in its documentation which says:
If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.
(emphasis mine)
Here's a way to avoid referencing a global variable at all in the method:
class example:
def fun1(self):
namespace = {}
exec("sent = {}", namespace)
sent = namespace['sent'] # Retrieve result.
print('in fun1, "sent" is now', sent )
return sent
v = example()
sent = v.fun1()
print('after calling fun1(), "sent" got set to', sent)
Output:
in fun1, "sent" is now {}
after calling fun1(), "sent" got set to {}
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is byreturn
ing them from the function/method. i.e.sent = v1.fun1()
(assuming you also put areturn sent
statement at the end of the method).
– martineau
Nov 19 at 21:49
add a comment |
up vote
1
down vote
up vote
1
down vote
You really should avoid using global variables. Regardless, here's how to do it:
class example:
def fun1(self):
# globals sent # Not needed in this special case.
exec("sent = {}", globals())
print('in fun1, "sent" is now', sent )
v = example()
print(v.fun1()) # Result will be None because fun1() doesn't return anything.
print('after call to fun1(), global "sent" is', sent)
Output:
in fun1, "sent" is now {}
None
after call to fun1(), global "sent" is {}
A global
declaration only does something inside a function or class method and even then is only needed when the global variable's value is going to be set to something.
However, as a special case, one isn't really needed here in the fun1()
method because it explicitly passes globals()
(but not a separate locals dict) when it calls exec()
. It might be a good idea to put one in anyway to make it more clear what's going on.
Using exec()
this way is explained in its documentation which says:
If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.
(emphasis mine)
Here's a way to avoid referencing a global variable at all in the method:
class example:
def fun1(self):
namespace = {}
exec("sent = {}", namespace)
sent = namespace['sent'] # Retrieve result.
print('in fun1, "sent" is now', sent )
return sent
v = example()
sent = v.fun1()
print('after calling fun1(), "sent" got set to', sent)
Output:
in fun1, "sent" is now {}
after calling fun1(), "sent" got set to {}
You really should avoid using global variables. Regardless, here's how to do it:
class example:
def fun1(self):
# globals sent # Not needed in this special case.
exec("sent = {}", globals())
print('in fun1, "sent" is now', sent )
v = example()
print(v.fun1()) # Result will be None because fun1() doesn't return anything.
print('after call to fun1(), global "sent" is', sent)
Output:
in fun1, "sent" is now {}
None
after call to fun1(), global "sent" is {}
A global
declaration only does something inside a function or class method and even then is only needed when the global variable's value is going to be set to something.
However, as a special case, one isn't really needed here in the fun1()
method because it explicitly passes globals()
(but not a separate locals dict) when it calls exec()
. It might be a good idea to put one in anyway to make it more clear what's going on.
Using exec()
this way is explained in its documentation which says:
If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.
(emphasis mine)
Here's a way to avoid referencing a global variable at all in the method:
class example:
def fun1(self):
namespace = {}
exec("sent = {}", namespace)
sent = namespace['sent'] # Retrieve result.
print('in fun1, "sent" is now', sent )
return sent
v = example()
sent = v.fun1()
print('after calling fun1(), "sent" got set to', sent)
Output:
in fun1, "sent" is now {}
after calling fun1(), "sent" got set to {}
edited Nov 20 at 0:32
answered Nov 19 at 19:54
martineau
65.2k987176
65.2k987176
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is byreturn
ing them from the function/method. i.e.sent = v1.fun1()
(assuming you also put areturn sent
statement at the end of the method).
– martineau
Nov 19 at 21:49
add a comment |
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is byreturn
ing them from the function/method. i.e.sent = v1.fun1()
(assuming you also put areturn sent
statement at the end of the method).
– martineau
Nov 19 at 21:49
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
it didn't work, it prints "None .. regarding to: "You really should avoid using global variables", what is the alternative in such a case?
– Ghanem
Nov 19 at 20:02
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is by
return
ing them from the function/method. i.e. sent = v1.fun1()
(assuming you also put a return sent
statement at the end of the method).– martineau
Nov 19 at 21:49
Ghanem: I think it works now, sorry about that. Alternatives to using globals depend on exactly what you're doing. The most common way is by passing them to the function/method as arguments (if they have mutable values). The other is by
return
ing them from the function/method. i.e. sent = v1.fun1()
(assuming you also put a return sent
statement at the end of the method).– martineau
Nov 19 at 21:49
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381248%2fexecute-script-from-string-with-accessing-the-variables%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Try: exec("global sent;sent = {}") . But avoid using global variables if you can.
– kantal
Nov 19 at 19:52
I can't add "global" to the string, because it's too long
– Ghanem
Nov 19 at 19:56
Ghanem: What do you mean it's too long? Strings can be almost any length in Python.
– martineau
Nov 20 at 0:40
It's a dataset, someone build it in a code format .. "dummy way"
– Ghanem
Nov 20 at 9:26