gpt4 book ai didi

python - 如何从只影响一个类的内置函数中导入对象?

转载 作者:太空狗 更新时间:2023-10-30 00:04:42 26 4
gpt4 key购买 nike

我正在使用 futurenewstyle 类的代码从 python2 转换为 python3。我的项目在 Django 1.11 中

我在 forms.py 中有一个类:

class Address:
...rest of code...

class AddressForm(Address, forms.ModelForm):
...rest of code...

在 Python 2 中

转换为:

from buitlins import object
class Address(object):
...rest of code...

class AddressForm(Address, forms.ModelForm):
...rest of code...

在 Python 3 中

我有一个 selenium 测试在转换为 Python3 后调用此表单时失败并出现以下错误:

File "<path_to_venv>/local/lib/python2.7/site-packages/django/utils/six.py", line 842, in <lambda>
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
File "<path_to_venv>/local/lib/python2.7/site-packages/future/types/newobject.py", line 78, in __unicode__
s = type(self).__str__(self)
RuntimeError: maximum recursion depth exceeded

但是,当我从 buitlins 导入对象中删除导入 时,测试通过了。

但是当我添加了 future 检查时,我得到了 future 差异错误&因此每个类都必须转换为新样式。我希望它在 Python2 和 Python3 中都能工作。

这个模块 builtins 模块导入是否可以只影响一个类而不影响 forms.py 文件中的其他类。还是有其他方法可以解决这个问题?

最佳答案

您遇到的问题似乎来自两个不同的 Python 2 现代化工具。您似乎正在使用 python_2_unicode_compatible来自 django.utils.six

的装饰器
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass

并继承自 newobject,它有这个 __unicode__方法

def __unicode__(self):
# All subclasses of the builtin object should have __str__ defined.
# Note that old-style classes do not have __str__ defined.
if hasattr(self, '__str__'):
s = type(self).__str__(self)
else:
s = str(self)
if isinstance(s, unicode):
return s
else:
return s.decode('utf-8')

并且由于两者在提供 __unicode____str__ 方法方面略有不同,因此它们会无限地相互调用,从而导致递归错误。

提供builtins.object的模块自己提供了python_2_unicode_compatible装饰器。您是否尝试过使用 django.utils.six 中的那个?

关于python - 如何从只影响一个类的内置函数中导入对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52078738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com