Jon Mills Jon Mills - 1 year ago 51
Python Question

How can I ignore Python 3 syntax when running script under Python 2?

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:

import unittest
import asyncio
# We must be running under Python 3 - run the sync and async tests.
except ImportError:
# We must be running under Python 2 - only run the sync tests.

class TestSyncMethods(unittest.TestCase):
def test_1(self):
# Test for synchronous functionality here

# Test for asynchronous functionality here
class TestAsyncMethods(unittest.TestCase):
@unittest.skipIf(not ASYNC_SUPPORTED, "Async not supported")
def test_async_1(self):
def go():
yield from sc.identify_a(1, 0x2B, True, True)

If I attempt to run this unittest under Python 2.x I get a syntax error at the "yield from" instruction, because "yield from" is not supported under Python 2.x. Ideally, I'd like to prevent the whole of the TestAsyncMethods class from being parsed if the unittest is being run under Python 2.x. Does anyone know a way to do it?

Answer Source

How about this:

from sys import version_info

if version_info[0] > 2:
    import asyncio
    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.