2

I'm using the six module in my program, and the code is as follows:

if six.PY2:
    do_something()
else:   
    do_something_else()

The problem with this approach is that, the function do_something_else() would run only if Python version is 3.4+ due to dependencies. (And not on Py 3.3)

How do I check for this?

Thanks a lot! :)

  • Are you asking how to check whether Python is version 3.4 or higher? – jwodder Jul 18 '17 at 21:31
  • 1
    Yes. I am curious to know if it's possible to check for the same using Six. –  Jul 18 '17 at 21:34
  • If you are concerned about different dependencies for v.2 vs. 3 - consider that ```import``` can be put under if/else clause. if condition: import something / else: import something_other – ddbug Jul 18 '17 at 22:11

2 Answers2

3

Since it's a common requirement, six already provides this one:

six.PY34

It will be true if the Python version is greater or equal than v3.4.

So you could do this:

if six.PY2:
    do_something()
elif six.PY34:   
    do_something_else()
else:
    # ...do what?
wim
  • 338,267
  • 99
  • 616
  • 750
  • It looks like they abandoned the two-digit scheme since 3.4. I have v3.6, and six.PY34 is True, but PY35 and PY36 are undefined and throw AttributeError. So, for example, one cannot test this way if F"..." strings are available. – ddbug Jul 18 '17 at 22:04
  • @ddbug You can not test if f string are available anyway, because that will be a syntax error at *import* time. So, your example is not a good one. – wim Jul 18 '17 at 22:19
  • I do not understand why you mentioned ```import``` here, but yes, both if and else paths must be understood by the actual compiler version, at compile time. Since import statements syntax is mostly same in v2 and 3, importing different things for v2 and 3 will work, import statements are executed in runtime. – ddbug Jul 18 '17 at 22:26
  • @ddbug It is an error at import time because the f-string syntax is invalid in anything older than Python 3.6. So, you wouldn't even be able to import a file that contained f-strings with Python 3.5, let alone test it with an if statement. – SethMMorton Jul 19 '17 at 02:47
  • Sorry, I shouldn't have mentioned f strings at all, it only added confusion. What I wanted to point out that suitable imports can be invoked in runtime, when the actual py version is known. And six.PYnn is not a reliable way to query for 3.x versions, `six` can only distinguish between py2 and py3. And even then the main file/module should not contain stuff that v2 cannot compile. – ddbug Jul 20 '17 at 12:32
2

You can get the actual version number as a tuple from sys.version_info. So:

if sys.version_info >= (3, 4):
    ...
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    And then you use lexicographical ordering of tuples: `sys.version_info >= (3, 4)` – wim Jul 18 '17 at 21:35