1

I have one basic question,I am declaring xmlfile as global in xml function,can I use it in another subroutine without any issues?does the order of subroutines matter?

 def xml():

        global xmlfile
        file = open('config\\' + productLine + '.xml','r')
        xmlfile=file.read()
 def table():
            parsexml(xmlfile)
1
  • ya,right,that was just a sample code..edited it Commented Nov 10, 2012 at 18:44

2 Answers 2

2

The order in which the functions are written does not matter. The value of xmlfile will be determined by the order in which the functions are called.

However, it is generally better to avoid reassigning values to globals inside of functions -- it makes analyzing the behavior of functions more complicated. It is better to use function arguments and/or return values, (or perhaps use a class and make the variable a class attribute):

def xml():
    with open('config\\' + productLine + '.xml','r') as f:
        return f.read()

def table():
     xmlfile = xml()
     parsexml(xmlfile)
Sign up to request clarification or add additional context in comments.

1 Comment

+1. globals are almost always the wrong solution to a problem.
0

First of all, I completely agree with the other comments about avoiding global variables. You should start by redesigning to avoid them. But to answer your question:

The order of definitions of the subroutine doesn't matter, the order in which you call them does:

>>> def using_func():
...   print a
... 
>>> using_func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in using_func
NameError: global name 'a' is not defined
>>> def defining_func():
...   global a
...   a = 1
... 
>>> using_func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in using_func
NameError: global name 'a' is not defined
>>> defining_func()
>>> using_func()
1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.