Why is this global variable telling me that the syntax is invalid?

Question:

So I’m making a project, and it will need stuff like datastores, so I’m creating a class that already have that handled for me.

Basically, I want my end result to look like this:

CoinStore = StoreService.FetchStore("CoinStore") # if coinstore exists, it will just refer from it, if not, create a datastore with the same name.
CoinStore.SaveData(50) # obviously 50 wouldn't be consistant for everyone, but just for the sake of this.

Basically my method is to create a text file, write all the data to it, and anytime it’s needed, refer right back to the store. Here is how I’m doing it:

class StoreService:
  def FetchStore(datastoreName):
    global datastore = open(datastoreName + ".txt", "w")
  def SetData(data):
    datastore.write(data)

But two problems arise:

  1. When you run the code, it tells you that there is a syntax error on line 3.
  2. I can’t seem to figure out why it won’t let you save integers, bools, etc, it only wants to take strings.

How can I fix all of this?

Edit for mpp:
Ok, I rewrote it as you said, now when I do:

hi = StoreService.FetchStore("hi")
hi.SetData("50")

It gives me the error:

Traceback (most recent call last): File "main.py", line 10, in <module> hi.SetData("50") AttributeError: 'NoneType' object has no attribute 'SetData'

And when I write it normally,

StoreService.FetchStore("hi")
StoreService.SetData("50")

Absolutely nothing happens, no errors, nothing is written.

Asked By: gamer merch

||

Answers:

  1. You are getting a syntax error because you can’t create a global variable and also give it a value on the same line. You would have to write it as:
class StoreService:
    def FetchStore(datastoreName):
        global datastore
        datastore = open(datastoreName + ".txt", "w")
    
    def SetData(data):
        datastore.write(data)
  1. When you write to a file, it will write it into the file as a string. You can’t save bool values or ints as their original type because you are writing them into a .txt file. They will be written and read as str.

Update: To fix your second issue, you are writing the code incorrectly for the task you are trying to do. Here is the correct formatting and syntax for classes:

class StoreService:
    def FetchStore(self, datastoreName):
        global datastore
        datastore = open(datastoreName + ".txt", "w")
    
    def SetData(self, data):
        datastore.write(data)
        datastore.close()

hi = StoreService()
hi.FetchStore("hi")
hi.SetData("50")
Answered By: mpp
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.