0

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

Benjels
  • 1
  • 1
  • 1
    I would imagine `set.add()` returns `None` so essentially you are using `global None`. You should just use `global desiredItems` and do the add on the next line. Although I would strongly recommend not using `global` and passing the set in as a parameter. – kylieCatt Nov 25 '14 at 06:05
  • @IanAuld, that would be a runtime error. In fact `global` must be followed by one or more _identifiers_, so the `.` causes it to be a syntax error – John La Rooy Nov 25 '14 at 06:11

2 Answers2

0

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

101
  • 8,514
  • 6
  • 43
  • 69
0

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502