<p>到目前为止,我能想到的最好的是一个包装器函数,它可以根据Python版本转换类型:</p>
<pre class="lang-python prettyprint-override"><code>from __future__ import unicode_literals
import sys
fromlist_expects_type = str
if sys.version_info < (3, 0):
fromlist_expects_type = bytes
def import_module(
name, globals=None, locals=None, fromlist=(), level=0):
""" Import specified module, together with options used by __import__.
:param module_name: Text string of the module name to import.
:param fromlist: List of names of attributes in the module to
also import.
:return: The module object.
The built-in ``__import__`` function accepts a ``fromlist``
parameter, but expects different string types between Python 2
and Python 3. Python 2 only allows text string items; Python 3
only allows byte string items.
This function's ``fromlist`` parameter must have items of text
string (Unicode) type only; the items are converted depending
on the running Python version.
"""
module_fromlist = ()
if fromlist:
module_fromlist = [
fromlist_expects_type(attr_name) for attr_name in fromlist]
module = __import__(
name=name,
globals=globals,
locals=locals,
fromlist=module_fromlist,
level=level)
return module
main_module_name = 'foo'
main_module = import_module(main_module_name, fromlist=['bar'])
</code></pre>
<p>这太难用了,我可能犯了几个错误。当然这是Python中的一个bug,我需要这样做吗?在</p>