mercredi 18 avril 2018

Does the Python if statement implicitly apply bool to objects found in the conditional?

I have a working selenium program that contains this code:

nxt_page = driver.find_element_by_class_name('btn--alt')
print(type(nxt_page))
if nxt_page:
    driver.execute_script('arguments[0].scrollIntoView();', nxt_page)
    print(type(nxt_page))
    nxt_page.click()

(see Scraping Duckduckgo with Python 3.6)

When the program runs, the two print statement show

<class 'selenium.webdriver.remote.webelement.WebElement'>
<class 'selenium.webdriver.remote.webelement.WebElement'>

Question: If you use an object for the [if conditional], like

if OBJECT:
    print('found')

is python simply substituting bool(OBJECT) for the conditional?

Is it always the case that bool(OBJECT) is False if OBJECT == None? I wouldn't think that a programmer could tamper with that. You could then equivalently write

if nxt_page != None:
    ect.

Before posting this I just found Boolean value of objects in Python , and that is certainly helpful.

Aucun commentaire:

Enregistrer un commentaire