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


Groups > comp.lang.python > #82554

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

References <85wq5tpe0g.fsf@benfinney.id.au>
From Devin Jeanpierre <jeanpierreda@gmail.com>
Date 2014-12-15 00:38 -0800
Subject Re: Portable code: __import__ demands different string types between 2 and 3
Newsgroups comp.lang.python
Message-ID <mailman.16977.1418632748.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Dec 14, 2014 at 11:29 PM, Ben Finney <ben+python@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

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


Thread

Re: Portable code: __import__ demands different string types between 2 and 3 Devin Jeanpierre <jeanpierreda@gmail.com> - 2014-12-15 00:38 -0800

csiph-web