Pass variables into and out of exec [closed for not being clear. Modified and reuploaded] [closed]

2024/10/5 19:18:03

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:

snip = '''
c = a+b
'''input_globals = {'a': 100, 'b': 2}
output_locals = {}exec(snip, input_globals, output_locals)
print(output_locals)

This results in the following output:

{'c': 102}

this effectively allows one to use exec "functionally", without working on and modifying global scope.

You can read this for more detail.

https://en.xdnf.cn/q/119183.html

Related Q&A

List Object Not Callable, Syntax Error for Text-Based RPG

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…

Why does my Tkinter window background not change?

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…

Combining a nested list without affecting the key and value direction in python

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…

Splitting very large csv files into smaller files

Is Dask proper to read large csv files in parallel and split them into multiple smaller files?

How to make this Python script to run subfolders too?

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

Why doesnt this recursive GCD function work? [duplicate]

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 …

How can I append \n at the end of the list in list comperhansion

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?[[., ., .],[., …

Seaborn bar plot y axis has different values than expected

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

Merge multiple JSON into single one (Python)

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 need to filter contents of my text file

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…