SyntaxError when adding to a global set inside a function (Python)

206 views Asked by At

I am trying to write a function that reads keywords from a file (in the format that each keyword is on a new line inside the text file)

I want the function to put the keywords into a global set() called "desiredItems".

desiredItems = set()

def populateDesired():
    for line in open("desireditems.txt"):
        addableLine = line.rstrip("\n")
        global desiredItems.add(addableLine)

For some reason my development environment (Pycharm) tells me that desiredItems.add is invalid syntax.

(sorry If I have inserted code snippet incorrectly etc)

Thanks in advance

2

There are 2 answers

0
101 On

You don't need to use global at all, just remove it.

1
John La Rooy On

If you need to modify the binding of a global variable, the syntax is like this

def populateDesired():
    global desiredItems
    for line in open("desireditems.txt"):
        addableLine = line.rstrip("\n")
        desiredItems.add(addableLine)

Since you are not modifying the binding - merely calling a method, there is no need for global here at all

def populateDesired():
    for line in open("desireditems.txt"):
        addableLine = line.rstrip("\n")
        desiredItems.add(addableLine)