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









share|improve this question
























  • 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















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









share|improve this question
























  • 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













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









share|improve this question















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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


















  • 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












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())





share|improve this answer





















  • 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




















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 {}





share|improve this answer























  • 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 returning 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











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















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

























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())





share|improve this answer





















  • 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

















up vote
1
down vote



accepted










You are not passing the global dictionary to modify. Try:



 exec("sent = {}",globals())





share|improve this answer





















  • 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















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())





share|improve this answer












You are not passing the global dictionary to modify. Try:



 exec("sent = {}",globals())






share|improve this answer












share|improve this answer



share|improve this answer










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




















  • 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














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 {}





share|improve this answer























  • 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 returning 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















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 {}





share|improve this answer























  • 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 returning 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













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 {}





share|improve this answer














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 {}






share|improve this answer














share|improve this answer



share|improve this answer








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 by returning 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


















  • 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 returning 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
















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 returning 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 returning 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


















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin