jawns317
jawns317

Reputation: 1746

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 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?

Upvotes: 21

Views: 4862

Answers (4)

rattray
rattray

Reputation: 6039

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.

Upvotes: 0

Ski
Ski

Reputation: 14487

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))

Upvotes: 11

AlexeyMK
AlexeyMK

Reputation: 6395

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.

Upvotes: 2

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

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

Upvotes: 4

Related Questions