compatibility - Python 3 backward compatability (shlex.quote vs pipes.quote) -
one of projects uses shlex.quote
available since python 3.3. shlex.quote
same pipes.quote
deprecated after moving shlex.
now compatibility using code:
def cmd_quote(string): import sys if int(sys.version[2]) < 3: import pipes homecoming pipes.quote(string) else: import shlex homecoming shlex.quote(string)
are improve practices exists?
first, if want numerical comparisons against version, utilize version_info
, don't seek parse string in version
.*
this means can take advantage of way tuples compared , write code like:
if sys.version_info < (3, 3):
… , won't break if python gets 3.10.0 or 4.0 ever come out.
* unless need worry 1.5 vs. 2.0, in case you've got time-machine gatewaying between usenet , stackoverflow, , certainly can think of improve uses that.
anyway, it's improve test shlex.quote
existing in first place. way, it's obvious reader you're doing: using shlex.quote
if possible, falling pipes.quote
if not.
you'll see pattern on place—even in stdlib, code imported c accelerator modules if possible, fallback code used if not (e.g., if you're using pypy instead of cpython).
also, note pipes.quote
only documented in 2.7. not 3.0-3.2 (which seems care about…), or 2.6, or other version. you're relying on happens there in particular implementation. (well, practically, in of them,* still, why rely on if don't have to?)
* far know, there aren't 3.2 implementations have pipes
, shlex
don't have pipes.quote
. , there won't many new 3.2 implementations created in future.
also, while can useful import
in middle of function, it's kind of weird thing do. if there's problem installation on machine deploy on, expect able import module successfully, later importerror
on calling function? that's kind of thing people baffled , run help time. :) (it's bit of performance nail looking in sys.modules
, converting strings ints , on when don't need to, uncertainty that's going matter.)
so, think way i'd write be:
try: shlex import quote cmd_quote except importerror: pipes import quote cmd_quote
python compatibility shlex
No comments:
Post a Comment