Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Python – What does _ do after a variable name

Sorry for my poor explanation but I’m reviewing my professor’s code like this:


              user, _ = User.objects.get_or_create(
                      name = serializer.data['name'],
                      email = serializer.data['email'],
                      password = make_password(serializer.data['password']))

when I remove the ", _" from that I can’t access the objects (eg: name) of it. I was doing
"user.name" but I cant without the ", _" can someone explain why that is.
It’s my first time here in in SO hehe

I wanna access the name field through the user where I assigned the object I created

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

_ is a variable, indeed _ is a valid variable name. _ is often used for "throw-away" variables: variables where we are not really interested in the result. The code you wrote is thus equivalent to:

user, created = User.objects.get_or_create(
    name=serializer.data['name'],
    email=serializer.data['email'],
    password=make_password(serializer.data['password']),
)

except that we now assigned it to a variable named created instead of _.

What is happening is that we "unpack" the 2-tuple of the result. Indeed, .get_or_create(…) [Django-doc] returns a 2-tuple:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

If you write:

x, y = some_2_tuple

it "unpacks" the some_2_tuple where x is assigned the first item of the 2-tuple, and y the second item. This can be extended to an arbitrary number of variables. For more information, see the extended iterable unpacking [pep].

when I remove the , _ from that I can’t access the objects (eg: name) of it. I was doing user.name.

If you remove the , _, it reads user = User.objects.get_or_create(…), so then user is a 2-tuple. You can access the user object then with user[0], so user[0].name, but likely unpacking is more convenient here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading