Compile time check of Python version

19 views
Skip to first unread message

Nikolaus Rath

unread,
Apr 28, 2013, 4:52:44 PM4/28/13
to cython...@googlegroups.com
Hello,

I have the following code:

def do_stuff(barf)
cdef char* buf
assert isinstance(barf, str)
if sys.version_info < (3,): # Python 3
barf_bytes = barf.encode('utf-8', 'surrogateescape')
else: # Python 2
barf_bytes = barf
buf = barf_bytes
# ...


However, I really dislike the runtime check on the Python version. In
theory, the condition could already be evaluated at C compile time.

Is there a way to do that? Unfortunately there seem to be no predefined
definitions for sys.version_info like there are for os.uname..


Best,

-Nikolaus

--
»Time flies like an arrow, fruit flies like a Banana.«

PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C

Stefan Behnel

unread,
Apr 29, 2013, 1:46:45 AM4/29/13
to cython...@googlegroups.com
Nikolaus Rath, 28.04.2013 22:52:
> I have the following code:
>
> def do_stuff(barf)
> cdef char* buf
> assert isinstance(barf, str)
> if sys.version_info < (3,): # Python 3
> barf_bytes = barf.encode('utf-8', 'surrogateescape')
> else: # Python 2
> barf_bytes = barf
> buf = barf_bytes
> # ...
>
>
> However, I really dislike the runtime check on the Python version. In
> theory, the condition could already be evaluated at C compile time.
>
> Is there a way to do that? Unfortunately there seem to be no predefined
> definitions for sys.version_info like there are for os.uname..

from cpython.version cimport PY_MAJOR_VERSION

if PY_MAJOR_VERSION < 3: ...

Stefan

Reply all
Reply to author
Forward
0 new messages