Solved

Problem recalling dictionary outside of def

Posted on 2007-11-27
9
302 Views
Last Modified: 2010-04-16
I am trying to recall a dictionary from a file which works fine only within the def DictionaryLoad() that I use to recall the file with. If I type in "Print UserData" within def DictionaryLoad() I get the UserData dictionary with the saved data. But If I recall it again later on (like I have in the code snippet) it only recalls the blank template of UserData. How do I fix this so that I can recall it later on in the code.
import pickle
 
UserData = {"Something": " ", "SomethingElse": " "}
 
def DictionaryLoad():
	file = open("UserData.dat", "r")
	UserData = pickle.load(file) #This works fine and I can recall UserData any were after this line in the def DictionaryLoad() area and it will have the saved data loaded from the UserData.dat file.
	file.close()
 
DictionaryLoad()
 
print UserData #only loads the blank UserData template here

Open in new window

0
Comment
Question by:ZoeticNepenthe
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 9

Expert Comment

by:ghostdog74
ID: 20363571
you need to return the value


 
def DictionaryLoad():
        file = open("UserData.dat", "r")
        UserData = pickle.load(file) #This works fine and I can recall UserData any were after this line in the def DictionaryLoad() area and it will have the saved data loaded from the UserData.dat file.
        file.close()
        return UserData
 
result = DictionaryLoad()
print result

Open in new window

0
 
LVL 29

Accepted Solution

by:
pepr earned 300 total points
ID: 20363596
Generally, using the same name outside def and inside def does not mean that you will work with the same data structure. Python uses the term "free variable" which means that your outer UserData could be used from inside your DictionaryLoad() only if the same name would not be assigned (bound) inside the body. Because you did assign the variable inside the body, the code of the body never see the outer UserData. See  Python Reference Manual section 4.1 Naming and binding for details (http://docs.python.org/ref/naming.html).

Ghostdog74's advice is perfect. All output values of a function should be returned this way. Notice that you can return more than one value in one return command.

I would add filename as the input argument of the DictionaryLoad() function.
def DictionaryLoad(filename):
        file = open(filename, "r")
        UserData = pickle.load(file)
        file.close()
        return UserData
 
UserData = DictionaryLoad("UserData.dat")

Open in new window

0
 
LVL 14

Assisted Solution

by:RichieHindle
RichieHindle earned 200 total points
ID: 20364073
Everyone above is right, but for completeness, there is a way to make your code work as it is.  The 'global' statement tells Python "When I assign to this name, I'm talking about the one outside my function, not within it."  Use it like this:
import pickle
 
UserData = {"Something": " ", "SomethingElse": " "}
 
def DictionaryLoad():
        global UserData
        file = open("UserData.dat", "r")
        UserData = pickle.load(file)
        file.close()
 
DictionaryLoad()
print UserData

Open in new window

0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 29

Expert Comment

by:pepr
ID: 20364902
RichieHindle: Oh, you should not tell him about the global at all :)))

No, just kidding ;) You should avoid using the global if possible for the same reasons as in other languages. As every value is passed by reference in Python, there is also a very small penalty for explicit passing (no cost of implicit copying).
0
 
LVL 1

Author Comment

by:ZoeticNepenthe
ID: 20365866
Why should I not use global? It seems to be the essayist way to do what I want to do.
0
 
LVL 14

Expert Comment

by:RichieHindle
ID: 20365950
ZoeticNepenthe: "Why should I not use global?"

Look at the core code of your module (ignoring the initialisation and the function definitions) using 'global' vs. using pepr's idea of returning the new dictionary:

# Using 'global':
DictionaryLoad()
print UserData

vs.

# Returning the new value (pepr's suggestion):
UserData = DictionaryLoad()
print UserData

In pepr's case, you can clearly see where UserData is coming from without having to go off and look at the definition of DictionaryLoad().  With the 'global' solution, it's not clear whether DictionaryLoad() will have any effect on UserData or not.

In a small script this probably doesn't matter very much, but in a larger application it can make a huge difference.
0
 
LVL 1

Author Comment

by:ZoeticNepenthe
ID: 20366405
So there is nothing significantly wrong with using global but when you return the new value like pepr suggested it is easier to keep your code clean and define variables.
0
 
LVL 29

Expert Comment

by:pepr
ID: 20366671
The problem with using global variables (also in other languages) may not be apparent in simple cases. The problem start to be tough when the global variable is shared by more functions.

When a function relies on status of a global variable or if it changes its content it influences behaviour of the other functions that also work with the global variable. The global variable makes the functions mutually dependent. When you add one more such function, you will add another piece of code that makes things even more dependent...

The problem is that it is difficult to design program that uses the functions in such a way that would produce correct results. Using the functions in slightly different order can cause problems that are difficult to debug because you, for example, did not think hard enough about the influence of the newly introduced function.
0
 
LVL 1

Author Comment

by:ZoeticNepenthe
ID: 20367454
ok, thank you all for your help. ^_^
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question