Reputation: 717
I'm having trouble importing a variable from a different python file to my current one. I know this has been asked several time previously and I have tried almost all those solutions, but no use.
In file top.py:
import sys, getopt, pdb
import argparse
import my_parser
my_parser.start_parse(6)
my_parser.in_out(2)
print "info: ",my_parser.verilog_inps
print "N1 data: ",my_parser.ckt_data["N1"]
In file parser.py (the first few lines only):
from collections import defaultdict
ckt_data = {}
global verilog_inps
verilog_inps = []
global verilog_outs
verilog_outs = []
global levels
levels = []
level_dict = defaultdict(list)
class ckt_elements:
delay = 0
inp_ = {}
out_ = {}
level = 0
change = False
prev = {}
typ_ = ""
def start_parse(a):
ckt_data["N1"] = a
def in_out(a):
verilog_inps = [a,a+1,a+2]
The strange thing is that I am able to access some variables and I am not able to do so for others (I declared the inaccessible ones global to see if that helps but no)
The aforementioned global variables are being modified in functions in parser.py.
So, my question: Why this strange behaviour? Am I doing something wrong? Using python 2.7
Please let me know if the question is not clear enough (I am at a loss to explain this better)
EDIT
I have solved the issue I am facing by using a global definition file.
In a separate file, I have declared the variables and then imported the file into all relevant files. (using import globals
)
In any case, I am very curious to know what was wrong with my previous approach.
Upvotes: 0
Views: 320
Reputation: 280207
The problem is that this function:
def in_out(a):
verilog_inps = [a,a+1,a+2]
don't actually affect the global verilog_inps
variable. It's assigning to a local. You need to put the global
declaration inside each function where you want to assign to the global variable:
def in_out(a):
global verilog_inps
verilog_inps = [a,a+1,a+2]
or assignments inside a function will cause the Python bytecode compiler to create a local variable with the same name and target the assignment to that variable.
Upvotes: 1