2

The following code works as expected

name = "Test"
myname = ""
exec('myname ="' + name + '"')
print(myname)

Which shows as result:

Test

Problem

However, if I define the same within a function in a class and execute it I get as result an empty string.

class new(object):
    def __init__(self, name):
        self.print(name)

    def print(self, name):
        myname = ""
        exec('myname ="' + name + '"')
        print(myname)

a = new("My name")

The above is a toy example code of a bigger code.

Question

How to define the function so as to get the same result? The exec function is actually needed in the bigger code.

3
  • 1
    Have you read the documentation for exec? What does it say about the behavior in local scopes? Hint, look at the last note. Commented Dec 21, 2022 at 20:24
  • Why are you using exec at all? I half suspect you don't need it as much as you think you do. Commented Dec 21, 2022 at 20:43
  • In this example case it's not needed of course. But in the real case I'm working in it's needed to shorten the code. Commented Dec 22, 2022 at 13:22

1 Answer 1

2

You can pass a dictionary as the globals (or locals) for exec.

def print(self, name):
    d = {"myname": ""}
    exec('myname ="' + name + '"', d)
    print(d["myname"])
Sign up to request clarification or add additional context in comments.

1 Comment

Is there no way to assign a value to a variable myname within the print function using the exec function? I tried what you proposed and it works. But I still can't create a variable named myname which gets what I want to be assigned. In particular in my bigger code I need a DataFrame get created using exec and then access one of it's columns. I may ask another question maybe...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.