[Tutor] Your dog Scope bit me!

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 20 Aug 2001 21:46:22 -0700 (PDT)

On Mon, 20 Aug 2001 fleet@teachout.org wrote:

> I'm trying to create a function that will retrieve a pickled dictionary.
> Python doesn't complain about the following; but I don't "get" anything
> and no "upc" is listed in dir().
> def get_upc():
>    """retrieves upc dictionary as upc"""
>    import pickle
>    f=open("upc.dict")
>    upc=pickle.load(f)
>    f.close()
>    print "UPC Dictionary retrieved"
> I'm assuming I have a scope problem.  Guess I don't understand all I
> should about scopes.  How do I run this from an interactive session so
> that I'm able to use the dictionary?

All functions by default will "return" a None value:

>>> def hello():
...     print "I still return None!"
>>> x = hello()
I still return None!
>>> x
>>> type(x)
<type 'None'>

To have the function return something more interesting, we should tell
Python what exactly to return back to the caller.  In get_upc(), the 'upc'
variable looks like our target:

def get_upc():
    """retrieves upc dictionary as upc"""
    import pickle
    f = open("upc.dict")
    upc = pickle.load(f)
    print "UPC Dictionary retrieved"
    return upc

Good luck!