kw_only和老虎机与旧版本的python兼容
我如何使用新的kw_only
和插槽
python 3.10的功能/dataclasses.html#dataclasses.dataclass“ rel =“ nofollow noreferrer”> dataclass
同时还支持旧版本的Python?
我要设置kw_only
的主要原因是,我可以拥有更多的置信度值转到正确的字段,而slots
是针对我可能创建大量的对象并且不需要不必要的dict
在幕后周围漂浮。
我最初认为使用类似的东西:
from dataclasses import dataclass
# check if we're using Python >= 3.10
if 'kw_only' in dataclass.__kwdefaults__:
_dataclass = dataclass
# redefine this to ignore new options
def dataclass(cls, *, kw_only=False, slots=False, **kwargs):
if cls is None:
return _dataclass(*kwargs)
return _dataclass(cls)
但是这导致Mypy抱怨重新定义的功能。
Python 3.8是我关心的最古老的版本。
How can I make use of the new kw_only
and slots
features available in Python 3.10's dataclass
while also supporting older version of Python?
The main reason I want to set kw_only
is so that I can have more confidence values go to the right field, and slots
is for an object I'm likely creating lots of and don't want an unnecessary dict
floating around behind the scenes.
I initially thought to use something like:
from dataclasses import dataclass
# check if we're using Python >= 3.10
if 'kw_only' in dataclass.__kwdefaults__:
_dataclass = dataclass
# redefine this to ignore new options
def dataclass(cls, *, kw_only=False, slots=False, **kwargs):
if cls is None:
return _dataclass(*kwargs)
return _dataclass(cls)
but this caused MyPy to complain about the function being redefined.
Python 3.8 is the oldest version I care about supporting personally.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经通过使用以下方法解决了这一点:
这个想法是定义一组可以扩展的词典,并将填写适当的参数。
我正在寻找
dataclass .__ kwdefaults __
检查当前Python解释器支持哪些参数。似乎也可以使用dataclass .__代码__。co_varnames
,但不是因为这需要更深入地看另一个级别。I've solved this by using:
the idea is to define a set of dictionaries that can be expanded and will fill out the appropriate parameters.
I'm looking in
dataclass.__kwdefaults__
to check which parameters are supported by the current Python interpreter. It also seems possible to usedataclass.__code__.co_varnames
but didn't because this requires looking another level deeper.