apronedsamurai
apronedsamurai

Reputation: 73

Functions and global scope/nested function confusion in python

fridge={"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":25} 
def fridge_function (fridge):
    del fridge["feta"]

    return

print (fridge)

I am confused.

1) I thought that the dictionary had global scope.

2) What I am trying to do is remove items from the dictionary, then update the amended dictionary as appropriate, i.e. remove the value "feta".

3) When I print fridge, I get the original list, in its unedited version. I even tried making a copy of the fridge, then trying to print that value outside of the function, but, the end result was the same: the original fridge dictionary with no modification.

Upvotes: 1

Views: 106

Answers (3)

thebjorn
thebjorn

Reputation: 27321

You're passing fridge in as a parameter, ergo it's going to be a local variable. To use the global fridge you would do:

FRIDGE = {"cheese": 10, "milk": 11, "feta": 12, "cream": 21, "onion": 32, "pepper": 25}

def fridge_function():
    del FRIDGE["feta"]

fridge_function()   # you need to call it
print(FRIDGE)

globals would normally be upper cased, so I've called the variable FRIDGE.

You'll need to add the global statement if you need to assign to the global variable (and only then):

def myfunction():
    global MYGLOBAL
    MYGLOBAL = 42

Using globals, and functions that mutate globals, are usually not a good solution however. Perhaps something object-oriented would be better? (Python 2.7 syntax):

class Fridge(dict):
    def __init__(self, **contents):
        super(Fridge, self).__init__(contents)

def main():
    fridge = Fridge(
        cheese=10,
        milk=11,
        feta=12,
        cream=21,
        onion=32,
        pepper=25
    )
    print fridge
    del fridge['feta']
    print fridge

if __name__ == "__main__":
    main()

the output is

{'cheese': 10, 'pepper': 25, 'feta': 12, 'onion': 32, 'milk': 11, 'cream': 21}
{'cheese': 10, 'pepper': 25, 'onion': 32, 'milk': 11, 'cream': 21}

Upvotes: 1

Stuart
Stuart

Reputation: 9858

For further clarification, note that either of the following will work:

With fridge as a function parameter:

fridge={"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":25} 
def fridge_function(fridge):
    del fridge["feta"]  # reference to fridge passed as a parameter

fridge_function(fridge)
print(fridge)

With fridge as a global variable

fridge={"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":25} 
def fridge_function():
    del fridge["feta"]  # refers to the global fridge 

fridge_function()
print(fridge)

The first is considered better programming style in most cases, as global variables are usually best avoided.

Upvotes: 2

Yoav Glazner
Yoav Glazner

Reputation: 8066

You haven't called the function fridge_function with fridge

This should work:

fridge_function(fridge)
print (fridge)

Upvotes: 3

Related Questions