Cris6556
Cris6556

Reputation: 1

#ifdef python3 print_with_parantheses #else print_using_python2_style #endif

Is there a way to achieve something like "conditional interpretation" in similar to the conditional compilation pre-processor directives allow? I would like to use the same code in Python 2.7 and Python 3, keeping the few -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

Answers (2)

phipsgabler
phipsgabler

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

HALF9000
HALF9000

Reputation: 628

Use from __future__ import print_function

You can check the documentation here: future.

Upvotes: 1

Related Questions