简体   繁体   English

Python 是否支持 object 文字属性值简写,如 ECMAScript 6?

[英]Does Python support object literal property value shorthand, a la ECMAScript 6?

In ECMAScript 6, I can do something like this...在 ECMAScript 6 中,我可以做这样的事情......

var id = 1;
var name = 'John Doe';
var email = 'email@example.com';
var record = { id, name, email };

... as a shorthand for this: ...作为这个的简写:

var id = 1;
var name = 'John Doe';
var email = 'email@example.com';
var record = { 'id': id, 'name': name, 'email': email };

Is there any similar feature in Python? Python有没有类似的功能?

No, but you can achieve identical thing doing this 不,但是您可以做到这一点

record = {i: locals()[i] for i in ('id', 'name', 'email')}

(credits to Python variables as keys to dict ) (将Python变量的信用作为dict的键

but I wouldn't do it because it compromises readability and makes static checkers incapable of finding undefined-name error. 但我不会这样做,因为它会损害可读性,并使静态检查器无法找到未定义名称的错误。

Your example, typed in directly in python is same as set and is not a dictionary 您直接在python中输入的示例与set相同,不是字典

{id, name, email} == set((id, name, email))

You can't easily use object literal shorthand because of set literals, and locals() is a little unsafe. 由于设置了文字,您不能轻易使用对象文字的简写,而locals()有点不安全。

I wrote a hacky gist a couple of years back that creates a d function that you can use, a la 几年前,我写了一个hacky gist ,它创建了一个可以使用的d函数,例如

record = d(id, name, email, other=stuff)

Going to see if I can package it a bit more nicely. 去看看我是否可以包装得更好。

No, there is no similar shorthand in Python. 不,Python中没有类似的速记。 It would even introduce an ambiguity with set literals, which have that exact syntax: 它甚至会引入带有set字面量的歧义,这些字面量具有确切的语法:

>>> foo = 'foo'
>>> bar = 'bar'
>>> {foo, bar}
set(['foo', 'bar'])
>>> {'foo': foo, 'bar': bar}
{'foo': 'foo', 'bar': 'bar'}

Yes, you can get this quite nicely with a dark magic library called sorcery which offers dict_of :是的,你可以使用一个名为sorcery的黑魔法库来很好地实现这一点,它提供了dict_of

x = dict_of(foo, bar)
# same as:
y = {"foo": foo, "bar": bar}

Note that you can also unpack like ES6:注意,你也可以像 ES6 一样解压:

foo, bar = unpack_keys(x)
# same as:
foo = x['foo']
bar = x['bar']

This may be confusing to experienced Pythonistas, and is probably not a wise choice for performance-sensitive codepaths.这可能会让有经验的 Python 爱好者感到困惑,并且对于性能敏感的代码路径来说可能不是一个明智的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM