KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is: from __future__ import print_function Compiling this module for Python 2.5 will fail with a: File "__init__.py", line 1 from __future__ import print_function SyntaxError: future feature print_function is not defined I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so. However, to quote PEP 236 : The only lines that can appear before a future_statement are: The module docstring (if any). Comments. Blank lines. Other future_statements. So I can't do something like: import __future__ if hasattr(__future__, 'print_function'): from __future__ import print_function else: raise ImportError('Python >= 2.6 is required') Because it yields: File "__init__.py", line 4 from __future__ import print_function SyntaxError: from __future__ imports must occur at the beginning of the file This snippet from the PEP seems to give hope of doing it inline: Q: I want to wrap future_statements in try/except blocks, so I can use different code depending on which version of Python I'm running. Why can't I? A: Sorry! try/except is a runtime feature; future_statements are primarily compile-time gimmicks, and your try/except happens long after the compiler is done. That is, by the time you do try/except, the semantics in effect for the module are already a done deal. Since the try/except wouldn't accomplish what it looks like it should accomplish, it's simply not al
Tags (comma-separated)
Save Edits
Cancel