3 ms·
If the source file contains syntax that is invalid on the user's Python version, then your code that's supposed to check the version and throw a helpful excepti
by teraflop 4y ago
If the source file contains syntax that is invalid on the user's Python version, then your code that's supposed to check the version and throw a helpful exception will never run. Instead the Python interpreter will throw a syntax error the first time it tries to parse something it doesn't recognize, and that syntax error may not make it obvious what the problem is.
- haihaibye 4y agoOk, that's a real problem, maybe we need a PEP for a minimum version in the header eg: # -*- python >= 3.1 -*- The trouble is, that wouldn't work on the old versions!
- tyingq 4y ago>The trouble is, that wouldn't work on the old versions! Yeah, a bit late to address the issue. Would have been helpful in the 2->3 transition.
- haihaibye 4y agoThe best time to adopt it was in 2.X, the second best time is now....
- indrora 4y agoPyPA has basically done that with pyproject.toml/Pipfile and pyenv.
- klysm 4y agoThis is a good point, but can’t you do it in __init__.py? I thought that ran first
- DecoPerson 4y agoAn entire file is parsed first, before any code in it is run. If your __init__.py didn’t have any version-specific syntax, then yes you could check the interpreter version before importing the rest of the files.
- jwilk 4y agoOne minor benefit of a compile-time version check, is that when the check fails, you're not left with useless .pyc files. Besides, __init__.py doesn't always exist.
- klyrs 4y agoIf you're trying to make a version-robust module that won't attempt to compile a syntax error, top-level dispatch through __init__.py is an excellent approach.