Pass variables into and out of exec [closed for not being clear. Modified and reuploaded] [closed]
2024/11/16 15:03:29
Given the following code
a = 100
b = 200snip = '''
c = a+b
'''exec(snip)
print(c)
how can I pass values into exec, and get values out of exec, without using global scope? In effect, I want to be able to explicitly control the entire scope exec has access to.
Answer
Generally, global scope is used with exec
a = 100
b = 200snip = '''
c = a+b
'''exec(snip)
print(c)
However, this can be problematic in some use cases. exec allows you to pass in a dictionary defining the global scope, and receive a dictionary containing the local scope. Here's an example:
Im having issues (still) with generating a random object, in this case a random herb found by foraging. Heres the code for the function:def collectPlants(self):if self.state == normal:print"%s spe…
Ive a small program with a feature to change the background color of a different window than the frame I use to ask for the background color. (I hope you understand this.) The program is written in Pyt…
I have a program that stores data in a list. The current and desired output is in the format:# Current Input
[{Devices: [laptops, tablets],ParentCategory: [computers, computers]},{Devices: [touch], Par…
Which part of the codes do I need to change in order to include subfolders?
File handle.py
import glob
import os
import sys
from typing import Listdef get_filenames(filepath: str, pattern: str) -> …
This question already has answers here:Why does my recursive function return None?(4 answers)What is the purpose of the return statement? How is it different from printing?(15 answers)Closed 1 year …
I have this code:def table(h, w):table = [[. for i in range(w)] for j in range(h)]return tablewhich returns this[
[., ., .], [., ., .], [., ., .], [., ., .]
]How to make it return this?[[., ., .],[., …
The y values in the Seaborn barplot are different than what my data shows.My data shows:yearmonth
2018-10 763308.0
2018-11 708366.0
2018-12 703952.0
2019-01 844039.0
2019-02 749583.…
I am searching for a way to merge multiple JSONs into a single one. My output is in this format:[{"Nome bollettino": "Bollettino 1"}, {"Causale": "1"}, {"Nu…
I have a text file that I want to loop through, slice some contents, and store in a separate list. The text file contains:blu sre
before we start
start the process
blah blah
blah blha
end the process
b…