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"?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cipher
  • 2,060
  • 3
  • 30
  • 58

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
  • 5,274
  • 6
  • 25
  • 37
DirtyBit
  • 16,613
  • 4
  • 34
  • 55