简体   繁体   中英

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

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

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?

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 )

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

{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.

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.

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'}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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