Is it possible to ignore or mask out pieces of Python 3 syntax when running script under Python 2?
I'm trying to write a unittest to run against a Python module under Python 2 or Python 3.
The test includes syntax that is only valid under Python 3 ("yield from") - and I only want to run those tests when I'm running the test on Python 3. Is there a method to disable or mask out this Python 3 code when I run it under Python 2 so that I don't get a syntax error being thrown when I run the unittest module?
See cut-down example below:
# We must be running under Python 3 - run the sync and async tests.
ASYNC_SUPPORTED = True
# We must be running under Python 2 - only run the sync tests.
ASYNC_SUPPORTED = False
# Test for synchronous functionality here
# Test for asynchronous functionality here
@unittest.skipIf(not ASYNC_SUPPORTED, "Async not supported")
yield from sc.identify_a(1, 0x2B, True, True)
How about this:
from sys import version_info if version_info > 2: ASYNC_SUPPORTED = True import asyncio else: ASYNC_SUPPORTED = True asyncio = None
As Alexander pointed out you will still need to split out in py2 and py3 modules. Unless you are going to get creative with exec, which I would highly recommend to avoid at almost all cost.