Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
jawns317 Avatar asked Feb 25 '15 15:02

jawns317


People also ask

What is object literal in Python?

A literal in both Python and JavaScript is a value that in the code represents itself, rather than acting as a reference to - or operations upon - other things in the code. Some simple examples include string and numerical literals in both Python and JavaScript ( 1 , "foo bar baz" , 3.1415 and so on).

What is object literal notation of JavaScript?

The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.

What Is syntax for computed names in object property definitions?

In ES6, the computed property name is a part of the object literal syntax, and it uses the square bracket notation. When a property name is placed inside the square brackets, the JavaScript engine evaluates it as a string. It means that you can use an expression as a property name.


3 Answers

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))
like image 171
Ski Avatar answered Oct 17 '22 09:10

Ski


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'}
like image 23
Stefano Sanfilippo Avatar answered Oct 17 '22 07:10

Stefano Sanfilippo


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.

like image 2
AlexeyMK Avatar answered Oct 17 '22 08:10

AlexeyMK