python2中的“ from Builtins import *”和super():不好的做法?

时间:2019-04-06 23:03:54

标签: python python-2.x

我正在尝试将我的Python3软件包反向移植到Python2。我使用了pasteurize,并且一切正常。我注意到它从builtins导入了一些内容,包括strintsuper。我想知道从builtins导入所有内容是否安全。是的,我知道原则上asterisk import is considered bad practice是因为它会使当前的名称空间混乱,并不能清楚地指出要导入的内容并覆盖您不想要的名称。但是特别是对于builtins来说,不是所有这些名称都已经作为名称出现,可以安全导入并且不应该破坏任何内容吗?

此外,如果在Python2代码中使用super中的builtins,是否可以不加任何参数地将其称为Python3的super呢?是否存在边缘情况可能会被Python2破坏?

from builtins import * # is this frowned upon?
from future import standard_library
standard_library.install_aliases()

class Foo(object):
    def __init__(self):
        super().__init__() # is this always safe in python 2?

编辑1 :需要说明的是,对于Python2,builtins来自future,它不是Python3中的内置模块。

编辑2 :有些人建议调用不带参数的super 从不可行,并且从builtins导入没有区别。显然这是错误的。

from __future__ import print_function

class Foo(object):
    def __init__(self, x):
        self.x = x

class Bar(object):
    def __init__(self, x):
        self.x = x + 1

class Baz(Bar, Foo):
    def __init__(self, x):
        super().__init__(x)

try:
    b = Baz(1)
except TypeError as e:
    # this will only happen in Python 2
    print("Didn't work: {}; trying with builtins.super".format(str(e)))
    from builtins import super
    b = Baz(1) # this now works in Python 2.7 too
print(b.x)

2 个答案:

答案 0 :(得分:1)

此super是可以正常工作的Python 3 super的重新实现,但不要指望它能像Python 3 super一样高效。

在Python 3中,编译器作弊,每当看到函数中引用的名称super时,它都会自动向该函数添加一个名为__class__的单元变量。 super函数利用__class__来弥补未传递给它的参数。您可以通过执行以下操作来看到实际效果:

class X:
    def f(self):
        super
        return __class__

assert X().f() is X
assert X.f.__closure__[0].cell_contents is X

__class__定义一次(第一次编译函数时)+,因此super进行的查找非常快。

另一方面,

newsuper需要每次向下钻取MRO(和任何装饰器),以找出self的类型和定义函数的类型。 这对于向后移植Python 3似乎很好(可能是为什么它存在于future.builtins中)。 但是,否则您应该坚持使用标准的Python 2 super ,这样,阅读您的代码的人就不会对此感到惊讶。

实施:(摘自https://github.com/rfk/magicsuper/blob/master/magicsuper/_super.py(如future.builtins.newsuper所述)

def super(typ=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
    '''Like builtin super(), but capable of magic.
    This acts just like the builtin super() function, but if called
    without any arguments it attempts to infer them at runtime.
    '''
    #  Infer the correct call if used without arguments.
    if typ is _SENTINEL:
        # We'll need to do some frame hacking.
        f = sys._getframe(framedepth)

        try:
            # Get the function's first positional argument.
            type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
        except (IndexError,KeyError,):
            raise RuntimeError('super() used in a function with no args')

        try:
            # Get the MRO so we can crawl it.
            mro = type_or_obj.__mro__
        except AttributeError:
            try:
                mro = type_or_obj.__class__.__mro__
            except AttributeError:
                raise RuntimeError('super() used with a non-newstyle class')

        #   A ``for...else`` block?  Yes!  It's odd, but useful.
        #   If unfamiliar with for...else, see:
        #
        #       http://psung.blogspot.com/2007/12/for-else-in-python.html
        for typ in mro:
            #  Find the class that owns the currently-executing method.
            for meth in typ.__dict__.itervalues():
                # Drill down through any wrappers to the underlying func.
                # This handles e.g. classmethod() and staticmethod().
                try:
                    while not isinstance(meth,FunctionType):
                        try:
                            meth = meth.__func__
                        except AttributeError:
                            meth = meth.__get__(type_or_obj)
                except (AttributeError, TypeError):
                    continue
                if meth.func_code is f.f_code:
                    break   # Aha!  Found you.
            else:
                continue    #  Not found! Move onto the next class in MRO.
            break    #  Found! Break out of the search loop.
        else:
            raise RuntimeError('super() called outside a method')

    #  Dispatch to builtin super().
    if type_or_obj is not _SENTINEL:
        return _builtin_super(typ,type_or_obj)
return _builtin_super(typ)

答案 1 :(得分:-1)

  

我注意到它从内置函数中导入了一些东西,包括str,int和super

您不需要{@ {1}}从bultins收集的东西,因为它们都是默认情况下导入的。

  

将其称为没有参数的Python3的import是否安全?

否-super不向后兼容,因此您必须在此处传递参数:

Python 3:

super

Python 2:

class Foo(object):
    def __init__(self):
        super().__init__()