luistripa luistripa - 4 months ago 9
Python Question

Using variables from other python files

I'm having some problems with this:

I have two files: random and random2

random has this:

import random2
print(random2.verb_list)
print(random2.x)


random2 has this:

verb_list = ['x', 'y', 'z']
other_list = ['1', '2', '3']
something_else = False

def Main():
global x
x = 1
print(verb_list)
if __name__ == "__main__":
Main()


It gives me this error when I run random:

AttributeError: module 'random2' has no attribute 'x'


Is there a way so I can call the variable x in random?
I have python3

Answer

The variable x is not created until the Main() function is run. Importing a module means that __name__ isn't set to __main__, so the function is never executed.

You must execute the Main() function. Put random2.Main() in the file random.py after the import line.

The name random is a very poor name for a module, since it collides with the standard python random module. It can create unexpected side effects.

Comments