user5740843 user5740843 - 5 months ago 8
Python Question

How to pass variables into next function without using global

I'm currently looking how I can take the variables that I've saved into the next function. To illustrate what I mean, I'm getting the latest version number online as such:

try:
webversion = urllib2.urlopen(
"http://www." + server + "/version").read().rstrip()
if webversion > version:
update_files()
elif version >= webversion:
print "[SYSTEM] You have the latest version: v." + version


In the
update_files()
function, I would very much like to take the variable I've gained (
webversion
and possibly
version
) over to the next function.

I'm thinking of setting this variable as global:

try:
global webversion
webversion = urllib2.urlopen(
"http://www." + server + "/version").read().rstrip()
if webversion > version:
update_files()
elif version >= webversion:
print "[SYSTEM] You have the latest version: v." + version


Is there a better way/smarter to do this?

Answer

just pass arguments to the function:

function definition:

def update_files(webversion, version):
    # ... function execution

and code:

try:
     # global webversion we don't need it
     webversion = urllib2.urlopen("http://www." + server + "/version").read().rstrip()
     if webversion > version:
          update_files(webversion, version)
     elif version >= webversion:
          print "[SYSTEM] You have the latest version: v." + version
#And be careful to add except, with try!
except:
    print("Error!")