9

I know that F Strings were introduce in Python 3.6. For that i was getting error - Invalid Syntax

DATA_FILENAME = 'data.json'
def load_data(apps, schema_editor):
    Shop = apps.get_model('shops', 'Shop')
    jsonfile = Path(__file__).parents[2] / DATA_FILENAME

    with open(str(jsonfile)) as datafile:
        objects = json.load(datafile)
        for obj in objects['elements']:
            try:
                objType = obj['type']
                if objType == 'node':
                    tags = obj['tags']
                    name = tags.get('name','no-name')
                    longitude = obj.get('lon', 0)
                    latitude = obj.get('lat', 0)
                    location = fromstr(F'POINT({longitude} {latitude})', srid=4326)
                    Shop(name=name, location = location).save()
            except KeyError:
                pass    

Error -

location = (F'POINT({longitude} {latitude})', srid=4326)
                                           ^
SyntaxError: invalid syntax

So i used -

fromstr('POINT({} {})'.format(longitude, latitude), srid=4326)

The Error was removed and it worked for me. Then i found this library future-fstrings. Should i use it. Which will remove the above Invalid Error

Cipher
  • 1,819
  • 1
  • 21
  • 48

1 Answers1

19

For older versions of Python (before 3.6):

Using future-fstrings:

pip install future-fstrings 

you have to place a special line at the top of your code:

coding: future_fstrings

Hence in your case:

# -*- coding: future_fstrings -*-
# rest of the code
location = fromstr(f'POINT({longitude} {latitude})', srid=4326)
ShivaGuntuku
  • 4,426
  • 4
  • 25
  • 36
DirtyBit
  • 16,151
  • 4
  • 28
  • 54
  • 4
    It is necessary that the statement starts from the hash mark, that is "# -*- coding: future_fstrings -*-", otherwise it won't work. Please, correct your answer. – Alexander Samoylov Dec 07 '20 at 11:29