Portable code: __import__ demands different string types between 2 and 3
Ben Finney
ben+python at benfinney.id.au
Mon Dec 15 20:36:04 EST 2014
Ethan Furman <ethan at stoneleaf.us> writes:
> On 12/14/2014 11:29 PM, Ben Finney wrote:
> > The ‘__import__’ built-in function, though, is tripping up.
>
> One work-around I have used is:
>
> if isinstance(some_var, bytes):
> some_var = some_var.decode('ascii')
> # at this point some_var is unicode in both Pythons
That's not the issue at all. I know how to declare a literal such that
it is Unicode in Python 2 and Python 3 (that's what the ‘from __future__
import unicode_literals’ does).
Rather, the problem is ‘__import__’ having incompatible expectations:
the ‘fromlist’ parameter's items must be bytes in Python 2, and must be
Unicode in Python 3.
The same parameter value can't satisfy both those requirements in a
single 2-and-3 compatible code base, without either using the
bytes-and-text ambiguity of ‘str’, or some kludge over-riding a simple
‘__import__’ call. Both of those are ugly and make for buggy code.
I'm increasingly of the opinion this is a subtle bug in ‘__import__’
that should be fixed instead of worked around. But it will likely be
rejected because the documentation advises against using ‘__import__’.
Bah.
--
\ “Try adding “as long as you don't breach the terms of service – |
`\ according to our sole judgement” to the end of any cloud |
_o__) computing pitch.” —Simon Phipps, 2010-12-11 |
Ben Finney
More information about the Python-list
mailing list