I've written a program which requires Python 3 (we will not be supporting Python 2) but I'd like to include an error message informing the user of this, should they accidentally run the .py file in Python2.
I tried to do this using a version check in the first few lines of the file:
import sys
if not sys.version_info[0] == 3:
sys.exit('You need to run this with Python 3')
# Lots of other code here....
# And then...
foo = 2
bar = 3
print(f"Some message that uses f-strings like this: variables are {foo} {bar}")
However, when the .py file is actually run using Python 2, it returns a syntax error on the line using f-strings. This is not very easy to understand.
Is there a way I can force the program to fail on the version check and thus, return the more useful error message?
Thanks
Is there a way I can force the program to fail on the version check and thus, return the more useful error message?
No, because Python first has to be able to parse and compile your file. That means you can only use supported syntax in the file, Python 2 can't parse f-strings.
You'll have to split up your project into multiple modules, and in the first module to be imported (say, the top-level __init__.py
file of a package), do your version check before you import other modules that rely on Python-3 specific syntax.
Or don't include such checks at all. Instead, set python_requires
for your project metadata, so that it won't be installed in older Python versions in the first place.