0

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?

1
  • no, no there isn't Commented Aug 31, 2021 at 10:52

2 Answers 2

1

Use from __future__ import print_function

You can check the documentation here: future.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thanks for the info, this actually solves my current problem. I guess the answer to the "conditional interpretation" question is no, isn't it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.