0

I am working on issue that I was thinking is a minor thing but I cannot get it to work. As in the title - I wrote a program that requires usage of python3.6+ due to f-strings presence. My intention is to catch the SyntaxError when user for example have python3.5 on his OS.

My initial idea:

def main():
    var = "more"
    print(f'I like f-strings a lot and {var}')

if __name__ == "__main__":
    if (sys.version_info.major == 3) and (sys.version_info.minor < 6):
        print("This program requires python3.6 or newer")
        print(old_python_error_message)
    else:
        print("Program starts...")
        main()

The problem is that I still got that error before script even starts.

Reason - as far as I researched - is:

You can only catch SyntaxError if it's thrown out of an eval, exec, or import operation.

Link: Failed to catch syntax error python

I still have no idea how can I do that in f-strins usage case.

Thanks for your time

szafran
  • 55
  • 1
  • 11
  • 1
    You can't. If you have an f-string in your code and you run it in a pre-fstring version of Python, you get a syntax error you can't catch, because Python cannot parse the file. – khelwood Jan 12 '21 at 04:14
  • How about using a package that backports f-strings to older Python versions - https://pypi.org/project/future-fstrings/ – Shiva Jan 12 '21 at 04:14
  • If you want to support code before 3.6, why don't you just not use f strings? – M Z Jan 12 '21 at 04:16
  • @MZ I don't want to "support" it. I want to give user useful feedback. Using f-strings was a blessing for me due toease of use. – szafran Jan 12 '21 at 05:48
  • @Shiva good to know but as above. I don't want to "support" it. Just to give feedback. – szafran Jan 12 '21 at 05:48

1 Answers1

1

It looks like all you want to do on pre-3.6 versions is report an error and terminate the program, and you just want a more user-friendly error message than a SyntaxError stack trace. In that case, instead of trying to catch a SyntaxError, have an entry point file that doesn't use f-strings, and do the version check there, before loading any code that uses f-strings:

# entry point
import sys

if sys.version_info < (3, 6):
    # report error, terminate program
else:
    import whatever
    whatever.main()
user2357112
  • 260,549
  • 28
  • 431
  • 505