0

I want a function, such that I send it a name (as string), and this function create a variable with that name and set its value to, say 5. That's it. When the function is done I should be able to access that variable in the main program.

To make a variable declared inside a function available outside, I use global. That's about as much as went with it. Here's my attempt for what its worth.

def func(name='a'):
    global exec(name)
    exec( name + '=5' )

func()
# now I should be able to access the variable a

It is not working BTW. PS: I know that the easy way is to just make the function return that thing and I assign it to whatever I want. But I want to do it the way I describe above.

Alex Deft
  • 2,531
  • 1
  • 19
  • 34
  • The second line in the function is perfect. But the error happens in the first line. – Alex Deft Jun 08 '19 at 23:39
  • 2
    Why would you *want* to do this? Define a known dict `d` globally, then set `d[name]` in `func`. – chepner Jun 08 '19 at 23:43
  • As to why I want to do that: it is a long story. But your solution is genius. Thank you. To summarize: make that variable in the main, give it a random value, put it in a dictionary so that functions can mutate it. Ask the function to mutate the value of that key in the dictionary. Genius! – Alex Deft Jun 08 '19 at 23:49

0 Answers0