[Tutor] Your dog Scope bit me!

Ignacio Vazquez-Abrams ignacio@openservices.net
Mon, 20 Aug 2001 23:21:16 -0400 (EDT)


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?
>
> Entering each of the lines in an interactive session retrieves the
> dictionary; but then I'm not in the "scope" of the function.
>
> 				- fleet -

Two options:

---
upc=None

def get_upc():
   global upc
    ...
---

---
def get_upc():
    ...
   return upc

 ...
upc=get_upc()
---

Either make it a global variable or return if from the function.

--
Ignacio Vazquez-Abrams <ignacio@openservices.net>