Reputation: 1
Is there a way to achieve something like "conditional interpretation" in python similar to the conditional compilation c pre-processor directives allow? I would like to use the same code in Python 2.7 and Python 3, keeping the few print-s that code has right now. That is, I would like to have syntactically incorrect code not interpreted in some cases.
A simple work-around like this one:
if sys.version_info.major == 3:
print("init message")
else:
print "init message"
results in a "SyntaxError: invalid syntax". Is there any way to tell the interpreter to skip evaluation?
Upvotes: 0
Views: 138
Reputation: 20950
You do it differently: instead of conditional interpretation, you use a __future__
statement, by which you can write code conforming to "future" syntax and keep backwards compatible:
from __future__ import print_function
print("init message")
A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard.
Upvotes: 0