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

Devin Jeanpierre jeanpierreda at gmail.com
Mon Dec 15 03:38:18 EST 2014


On Sun, Dec 14, 2014 at 11:29 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> I'm slowly learning about making Python code that will run under both
> Python 2 (version 2.6 or above) and Python 3 (version 3.2 or above).
>
> This entails, I believe, the admonition to ensure text literals are
> Unicode by default::
>
>     from __future__ import unicode_literals

Ordinarily, for 2.x/3.3+ code I would suggest not doing this --
instead, b'...' for bytes, u'...' for unicode, and '...' for native
"string" type (bytes on 2.x, unicode on 3.x). This is the main benefit
of the u'...' syntax addition.

For 3.2, you'll have to do b'...' for bytes, '...' for unicode, and
str('...') for platform-specific strings (bytes on 2.x, unicode on
3.x).  It is in good taste to make an alias of str so it's less
confusing, e.g. native_str = str.

So for example, it's __import__(str("foo")), and getattr(foo, str("bar"), baz).

-- Devin



More information about the Python-list mailing list