Solved

Problem recalling dictionary outside of def

Posted on 2007-11-27
9
303 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
On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

 
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

Enroll in June's Course of the Month

June's Course of the Month is now available! Every 10 seconds, a consumer gets hit with ransomware. Refresh your knowledge of ransomware best practices by enrolling in this month's complimentary course for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

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

This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
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 strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

705 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