0

I have a couple of Python files which generates following error:

In Globals.py

def init():
    global duty

In SCDetail.py

import Globals
#############################################################
def classify_nodes(sample_no):

filename='Sample_'+str(sample_no)+'_TDinfo.txt'
fh=open(filename,'r')

for line in fh:
    tempList=line.split(':')
    duty[tempList[0]]=tempList[1]
    tax[tempList[0]]=tempList[2]
#############################################################
def complete_SC_detail(sample_no,num_periods,vertex1_body):

    Globals.init()
    sample_no=1
    classify_nodes(sample_no)

In Simple.py

import SCDetail
SCDetail.complete_SC_detail(1,3,3)

(I have other functions that use the globals defined in Globals.py, in simple.py and scdetail.py. But I just gave the code mentioned in the traceback.)

When I run Simple.py, I am getting following error:

global name 'duty is not defined

I will be glad if someone can help me identify what I am missing...

Edit: I am not looking for generic explanation. I am trying to apply a method that was suggested by a previous comment and trying to locate the specific problem in the above implementation.

Ozgu
  • 151
  • 1
  • 12
  • 1
    Globals are only ever global in their own module. They don't set globals elsewhere. – Martijn Pieters Apr 20 '16 at 17:52
  • You can use duty variable through the module: Globals.duty[tempList[0]]=tempList[1], but it's not so good practice – Peter Apr 20 '16 at 17:57
  • You could simply refer to the name in the other module: `Globals.duty` instead of `duty`. – Martijn Pieters Apr 20 '16 at 17:58
  • How about this answer: http://stackoverflow.com/questions/13034496/using-global-variables-between-files-in-python @Hai Vu claims this approach should work?? – Ozgu Apr 20 '16 at 21:29
  • I guess I should be referring module variables with their module names as well. Thanks for the suggestion @Petr.. – Ozgu Apr 21 '16 at 11:23
  • `global duty` need only when you have to assign some value to duty in the local scope. So if you perform `duty=2` in the init after `global duty` you change a variable declared at module level, and in case if in the init would not be `global duty` you simply would create a new variable. – Peter Apr 21 '16 at 11:50

0 Answers0