"from builtins import *" 和 python2 中的 super():不好的做法?
"from builtins import *" and super() in python2: bad practice?
我正在尝试将我的 Python3 包移植到 Python2。我使用 pasteurize
并且一切正常。我注意到它从 builtins
导入了一些内容,包括 str
、int
和 super
。我想知道从 builtins
导入所有内容是否安全。是的,我知道原则上 asterisk import is considered bad practice 因为它扰乱了当前的命名空间,并不清楚导入的内容和覆盖你不想要的名称。但是,当谈到 builtins
时,难道不是所有这些都已经作为名称存在,可以安全导入并且不应该破坏任何东西吗?
此外,如果在 Python2 代码中使用 builtins
中的 super
,将其称为 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
never 并且从 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)
这个 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)
我正在尝试将我的 Python3 包移植到 Python2。我使用 pasteurize
并且一切正常。我注意到它从 builtins
导入了一些内容,包括 str
、int
和 super
。我想知道从 builtins
导入所有内容是否安全。是的,我知道原则上 asterisk import is considered bad practice 因为它扰乱了当前的命名空间,并不清楚导入的内容和覆盖你不想要的名称。但是,当谈到 builtins
时,难道不是所有这些都已经作为名称存在,可以安全导入并且不应该破坏任何东西吗?
此外,如果在 Python2 代码中使用 builtins
中的 super
,将其称为 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
never 并且从 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)
这个 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)