luistripa luistripa - 1 year ago 97
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

random2 has this:

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

def Main():
global x
x = 1
if __name__ == "__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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download