最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does Python support object literal property value shorthand, a la ECMAScript 6? - Stack Overflow

programmeradmin1浏览0评论

In ECMAScript 6, I can do something like this ...

var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { id, name, email };

... as a shorthand for this:

var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { 'id': id, 'name': name, 'email': email };

Is there any similar feature in Python?

In ECMAScript 6, I can do something like this ...

var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { id, name, email };

... as a shorthand for this:

var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { 'id': id, 'name': name, 'email': email };

Is there any similar feature in Python?

Share Improve this question edited Feb 25, 2015 at 15:28 thefourtheye 239k53 gold badges465 silver badges500 bronze badges asked Feb 25, 2015 at 15:26 jawns317jawns317 1,7462 gold badges17 silver badges26 bronze badges 2
  • possible duplicate of Python variables as keys to dict – Bhargav Rao Commented Feb 25, 2015 at 15:28
  • 4 Nop, { id, name, email } is a set-literal in Python. – Ashwini Chaudhary Commented Feb 25, 2015 at 15:28
Add a comment  | 

4 Answers 4

Reset to default 11

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)

Your example, typed in directly in python is same as set and is not a dictionary

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

No, there is no similar shorthand in Python. It would even introduce an ambiguity with set literals, which have that exact syntax:

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

You can't easily use object literal shorthand because of set literals, and locals() is a little unsafe.

I wrote a hacky gist a couple of years back that creates a d function that you can use, a la

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

Going to see if I can package it a bit more nicely.

Yes, you can get this quite nicely with a dark magic library called sorcery which offers dict_of:

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

Note that you can also unpack like 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论