Global Variable in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I am very new to Python. Not learnt classes yet. Using Python 3.2.2. Tried implement some procedural C logic. My code is spread over 2 files as follows.

this file is called date.py

dd,mm,yy=0,0,0

def isValidDate(d,m,y):
    if(d>=1 and d<=31 and m>=1 and m<=12):
        dd,mm,yy=d,m,y #problem
        print(dd,mm,yy) #problem
        print(d,m,y) #problem
        return True
    else:
        return False

def printDate():
    print(dd,mm,yy) #problem

this file is called module1.py

import date

def main():
    dd,mm,yy = 23,1,1984
    valid = date.isValidDate(dd,mm,yy) #problem
    print (valid)
    date.printDate()
    date.dd=22 #problem
    date.printDate()

if __name__ ==  __main__ :
    main()

The lines that I have commented as "problem" are giving me problems.

When the statement in module1.py (which is "date.dd=22") executes, the value of the global variable in date.py changes to 22 and stays that way.

But when I call the isValidDate() function, even though the test condition is passed, the assignment does not seem to be permanent. The local print statement in isValidDate() function shows that "dd" is assigned the value, but in the main() function the call to printDate() shows the original values.

What is going on?

Answers

To assign values to a global variable in your code you ve got to mark it as such, otherwise the code would be assigning to a local variable with the same name (that would be actually shadowing the global variable).

http://docs.python.org/reference/simple_stmts.html#the-global-statement http://docs.python.org/reference/simple_stmts.html#the-global-statement

It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

Hence, to fix the problem, you d need something like this:

def isValidDate(d,m,y):
    if(d>=1 and d<=31 and m>=1 and m<=12):
        global dd, mm, yy
        dd,mm,yy=d,m,y
        ...

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8883000/global-variable-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils