Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #82570

Re: Portable code: __import__ demands different string types between 2 and 3

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: Portable code: __import__ demands different string types between 2 and 3
Date 2014-12-16 12:36 +1100
References <85wq5tpe0g.fsf@benfinney.id.au> <548F18FC.5040408@stoneleaf.us>
Newsgroups comp.lang.python
Message-ID <mailman.16991.1418693773.18130.python-list@python.org> (permalink)

Show all headers | View raw


Ethan Furman <ethan@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

Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Re: Portable code: __import__ demands different string types between 2 and 3 Ben Finney <ben+python@benfinney.id.au> - 2014-12-16 12:36 +1100
  Re: Portable code: __import__ demands different string types between 2 and 3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-12-16 13:32 +1100
    Re: Portable code: __import__ demands different string types between 2 and 3 Ben Finney <ben+python@benfinney.id.au> - 2014-12-16 14:07 +1100

csiph-web