Seems like I want a pre-processor, but...
Fredrik Lundh
fredrik at pythonware.com
Tue Mar 28 11:27:49 EST 2006
Russell Warren wrote:
> 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.
the collections module was added in 2.4, so it's not clear what code you're
really using under 2.3. but since it's not a standard module, maybe you could
add the missing method yourself ?
> 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?
fork the function/method:
if sys.version_info < (2, 4):
def myfunc(self):
# using deque emulation
return self.myDeque.pop(0)
else:
def myfunc(self):
return self.myDeque.popleft()
or wrap the non-standard deque class in a compatibility wrapper:
if sys.version_info < (2, 4):
class mydequeclass(deque):
def popleft(self):
return self.pop(0)
...
return self.myDeque.popleft()
</F>
More information about the Python-list
mailing list