1

The following is a snippet of my code. When I tried running this, the error states that 'self' is not defined. I copied this code online because I don't really know how to use the function user_data_dir. I know that it works (I'm using Windows to write this) with just store = JsonStore('user.json') but I've been reading that using the function user_data_dir would be useful because it is a general function that creates a writeable path for various systems. Would be great if someone could help explain this!

from kivy.storage.jsonstore import JsonStore
from os.path import join

data_dir = getattr(self, 'user_data_dir')
store = JsonStore(join(data_dir,'user.json'))

class Welcome(Screen):
    pass
Shuet Ling
  • 23
  • 4
  • 2
    `user_data_dir` is an attribute of the App class. Your code expects to be called from a method of the App class, such as the `build` method, in which case `self` is the instance of the class. – inclement Oct 30 '17 at 23:48

1 Answers1

2
data_dir = getattr(self, 'user_data_dir')

When you copied this line, it was somewhere inside some class's function:

class Some:
    def func(self):
        data_dir = getattr(self, 'user_data_dir')

Method located inside class in Python receives self as first parameter.

But not every object has user_data_dir attribute: as inclement noticed above it's App objects attribute. You should do something like:

class MyApp(App):
    def build(self):

        data_dir = getattr(self, 'user_data_dir')
        store = JsonStore(join(data_dir,'user.json'))

        # ...

Upd:

You can store path to json file inside app class and access to app instance to get this path with App.get_running_app():

class MyApp(App):
    @property  # see https://www.programiz.com/python-programming/property
    def storage(self):
        return join(self.user_data_dir, 'user.json')

and later in any place you want:

class SomeClass():
    def some_func(self):
        print('here\'s our storage:', App.get_running_app().storage)
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
  • Hi, so does that mean that I have to put that in every class in which there is the need to save a json file? Like I have multiple screens and each screen is a class in my code, and under some of the screens, I will want to save some data into a json file. Should I have to include the two lines (the one with data_dir =, and also store = ) under each of those classes? – Shuet Ling Oct 31 '17 at 16:40
  • just to clarify my comment above, I tried adding the two lines to just the app class, but elsewhere that has the function 'store.get(..)' does not work because they say store is not defined – Shuet Ling Oct 31 '17 at 17:03
  • @ShuetLing I updated answer with example of how it can be solved. – Mikhail Gerasimov Oct 31 '17 at 17:17