I was reading an article(https://www.techgeekbuzz.com/blog/how-to-read-emails-in-python/) that describes how to read emails using python, now its using _, before declaring a variable here is the code:
#modules
import imaplib
import email
#credentials
username ="[email protected]"
#generated app password
app_password= "aqwertyuiopasdfa"
# https://www.systoolsgroup.com/imap/
gmail_host= 'imap.gmail.com'
#set connection
mail = imaplib.IMAP4_SSL(gmail_host)
#login
mail.login(username, app_password)
#select inbox
mail.select("INBOX")
#select specific mails
_, selected_mails = mail.search(None, '(FROM "[email protected]")')
#total number of mails from specific user
print("Total Messages from [email protected]:" , len(selected_mails[0].split()))
for num in selected_mails[0].split():
_, data = mail.fetch(num , '(RFC822)')
_, bytes_data = data[0]
#convert the byte data to message
email_message = email.message_from_bytes(bytes_data)
print("\n===========================================")
#access data
print("Subject: ",email_message["subject"])
print("To:", email_message["to"])
print("From: ",email_message["from"])
print("Date: ",email_message["date"])
for part in email_message.walk():
if part.get_content_type()=="text/plain" or part.get_content_type()=="text/html":
message = part.get_payload(decode=True)
print("Message: \n", message.decode())
print("==========================================\n")
break
Why is _, used every-time I remove it, it gives an error so I just wanna know what it does.
Thanks!!
CodePudding user response:
I think your question is unclear as it seems to be asking about leading underscores in variable names but the example code you provide is a variable who's who name is just _
.
In the case of the former, leading underscores in variable names (eg. _myVariable
), according to PEP8 is meant to denote that variable should only be used internally. Python doesn't have the concept of enforced access modifiers (think: public
, private
etc. in Java) so these things are instead hinted at via naming conventions (such as leading underscores in variable names. You might also be interested in reading about dunder variables).
In case of the latter (a single _
) I think it's meant to clearly show that the writer of this code has no intention of actually using this variable, which it does so effectively. As for why you have to have it in your code, and why removing it breaks your code, this is because regardless of whether or not you want to use the variable, the IMAP4.search(...)
function returns two values as you can see in the documentation here.
CodePudding user response:
What you see is simply unpacking a tuple, like
var1, var2 = (123, 345)
The _
is just a variable name. However, it is used to indicate that the variable is not used anywhere.