0

So I'm making a program and I have made a module to go along with it. In the module I have a function where I use exec() to create a global variable:

def FunctionName(headings):
    for c in headings:
        exec('global %s' % c)
<Other code...>

And I have another script:

import modulename
headings = ['test1','test2','test3']
modulename.FunctionName(headings)
print(dir(modulename))
print(modulename.test1)

But this returns

['FunctionName',<Other function but no variables>]
Traceback (most recent call last):
File "<path>\main_program.py", line 6, 
in <module>
print(modulename.test1)
AttributeError: module 'modulename' has no attribute 'nice'

If I manually say

global <Var name>

in the module, it works fine. Any ideas why and how to fix?

ScottBot10
  • 153
  • 2
  • 10
  • Possible duplicate of [Creating variable number of variables in python](https://stackoverflow.com/questions/45015360/creating-variable-number-of-variables-in-python) – Devesh Kumar Singh May 30 '19 at 13:09
  • 3
    The way to fix it is *not to do this*. Each of `exec` and `global` are bad enough on their own, the combination is just horrible. Why are you doing this? Have you thought about using a class for the global state? – Daniel Roseman May 30 '19 at 13:11

0 Answers0