Solved

Problem recalling dictionary outside of def

Posted on 2007-11-27
9
292 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
  • 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 28

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
 
LVL 28

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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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 28

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
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 …

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now