Does Python support literal object property value, 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 a similar function in Python?

+6
source share
3 answers

No, but you can achieve the same thing by doing this

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

(credits python variables as keys to dict )

but I wouldn’t do it, because it compromises readability and makes static checkers unable to find the undefined -name error.

Your example entered directly in python is the same as installed and is not a dictionary

 {id, name, email} == set((id, name, email)) 
+2
source

No, there is no similar reduction in Python. It even introduces ambiguity with set literals that have this exact syntax:

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

You cannot easily use object literal reduction because of a set of literals, and locals() little unsafe.

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

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

Let's go see if I can pack it a little prettier.

0
source

Source: https://habr.com/ru/post/982993/


All Articles