In Javascript, I can use destructuring to extract properties I want from a javascript objects in one liner. For example:
currentUser = {
"id": 24,
"name": "John Doe",
"website": "http://mywebsite.com",
"description": "I am an actor",
"email": "[email protected]",
"gender": "M",
"phone_number": "+12345678",
"username": "johndoe",
"birth_date": "1991-02-23",
"followers": 46263,
"following": 345,
"like": 204,
"comments": 9
}
let { id, username } = this.currentUser;
console.log(id) // 24
console.log(username) //johndoe
Do we have something similar in Python for Python dicts and Python objects? Example of Python way of doing for python objects:
class User:
def __init__(self, id, name, website, description, email, gender, phone_number, username):
self.id = id
self.name = name
self.website = website
self.description = description
self.email = email
self.gender = gender
self.phone_number = phone_number
self.username = username
current_user = User(24, "Jon Doe", "http://mywebsite.com", "I am an actor", "[email protected]", "M", "+12345678", "johndoe")
# This is a pain
id = current_user.id
email = current_user.email
gender = current_user.gender
username = current_user.username
print(id, email, gender, username)
Writing those 4 lines (as mentioned in example above) vs writing a single line (as mentioned below) to fetch values I need from an object is a real pain point.
(id, email, gender, username) = current_user
print(currentUser['id'])
in Python?User
), see the attrs library: attrs.org/en/stable. Or there is this approach:self.__dict__.update(locals())
User
, you could define a custom__str__
. If you just need those attributes in a group from time to time, you could define a method that returns such.