[Tutor] Returning a variable from a module
Glen Wheeler
wheelege@tsn.cc
Mon, 9 Jul 2001 00:26:12 +1000
> <..snip!..>
>
> It seems to work, but when I save this code into a file called
> configlib.py and try to get values from the variable config. It doesnt
> seem to work.
>
> import configlib
> configlib.import('.gamerc')
>
> This leads to my question: How do I access a variable that I have created
> within a module which I have imported?
>
Hmmm, well it's as simple as this...
def dosomething(args):
..code..
return result ## important!
So, in your code, just return that config dictionary. Try to avoid global
variables, as they aren't too crash hot.
##
global config
config = {}
for n in range(1, len(configList)):
splitString = string.split(configList[n], '=')
config[splitString[0]] = splitString[1]
##
Would become...
##
config = {}
for n in range(1, len(configList)):
splitString = string.split(configList[n], '=')
config[splitString[0]] = splitString[1]
return config
##
And would be called like this...
import configlib
config = configlib.import('.gamerc')
Like magic, the variable config now has that dictionary you made in the
other module.
Quick question about your code - shouldn't this...
for n in range(0, len(configList)):
configList[n] = string.rstrip(configList[n])
configList[n] = string.lstrip(configList[n])
configList[n] = string.replace(configList[n], '\012', '')
Be...
for n in range(0, (len(configList)-1)):
configList[n] = string.rstrip(configList[n])
configList[n] = string.lstrip(configList[n])
configList[n] = string.replace(configList[n], '\012', '')
?? Either that or I really am poor tonight :)
HTH,
Glen.