Seems like I want a pre-processor, but...

Peter Otten __peter__ at web.de
Tue Mar 28 18:42:00 CEST 2006


Russell Warren wrote:

> After some digging it seems that python does not have any equivalent to
> C's #if directives, and I don't get it...
> 
> For example, I've got a bit of python 2.3 code that uses
> collections.deque.pop(0) in order to pop the leftmost item.  In python
> 2.4 this is no longer valid - there is no argument on pop (rightmost
> only now) and you call .popleft() instead.

collections is new in 2.4 -- I assume you mean list.pop(0) versus
collections.deque.popleft().

> I would like my code to work in both versions for now and simply want
> to add code like:
> 
> if sys.version[:3] == "2.3":
>   return self.myDeque.pop(0)
> else:
>   return self.myDeque.popleft()
> 
> but am recoiling a bit at the unnecessary conditional in there that I
> think will be run on every execution - unless the compiler has some
> magic detection of things like sys.version to compile out the
> conditional as if it were a preprocessor directive (seems highly
> unlikely!)?.
> 
> What is the pythonic thing to do?  This is in a generally usable file,
> not a package, so I don't want to make a version for each (which seems
> to be what every package out there does).  It seems to be begging for a
> pre-processor directive set.

Here's how I would rewrite your example:

try:
    from collections import deque
except ImportError:
    class deque(list):
        def popleft(self):
            return self.pop(0)

# in your method:
        return self.myDeque.popleft()

That way the performance impact almost vanishes for the newer python and
your code is less cluttered with if ... else statements that are only there
to pick the version specific code.

Peter



More information about the Python-list mailing list