pythonf-stringversion-detection

Can I assert the python version before the interpreter parses the code?


I want to inform the user which python version they should use:

import sys
assert sys.version_info >= (3, 6), "Use Python 3.6 or newer"
print(f"a format string")

But instead, running the above file makes a syntax error:

$ python fstring.py. # default python is 2.7
  File "fstring.py", line 3
    print(f"a format string")
                           ^
SyntaxError: invalid syntax

Is it possible to do this per-file, without wrapping all the f-strings inside of try blocks?


Solution

  • No, this is not possible on a per-file basis, because parsing happens for the whole file before any of it is executed, and therefore before any assertions are checked. try also won't work, for the same reason.

    The only way this could possibly work is if you defer the parsing of part of the code until runtime by putting the code in a string and calling eval, but... don't do that. You have two sensible options: don't use f-strings at all, or let it fail with a SyntaxError instead of your own custom error message.

    Alternatively, if you are working on a Unix or Linux system then you can mark the file as executable and give it a shebang line at the start like #!/usr/bin/python3.8 so that the user doesn't need to know the right version to use themselves.

    If you want to do this on a per-module basis instead, see @Chris's answer.