1

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 is not None:
    ect.

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

CopyPasteIt
  • 532
  • 1
  • 8
  • 22
  • 1
    take a look at this: https://docs.python.org/3/reference/datamodel.html#object.__bool__ – spooky Apr 18 '18 at 20:54
  • Yes. 11 more characters to go... – BallpointBen Apr 18 '18 at 20:54
  • 1
    In that link you provided, had a link to the Python docs to [`__nonzero__`](https://docs.python.org/2/reference/datamodel.html#object.__nonzero__) which says that internally `bool()` checks `__nonzero__` first, then `__len__` functions. – Sunny Patel Apr 18 '18 at 20:55
  • 1
    The linked question seems to answer your question, so I'm not really sure what you're asking. It isn't always the case that `bool(OBJECT)` is False if `OBJECT == None` because one can be customized with `__bool__` and the other with `__eq__` – miradulo Apr 18 '18 at 20:57
  • 1
    `__nonzero__` predates `bool` and is not used in 3.x. Tests for `None` should use `is` or `is not`. – Terry Jan Reedy Apr 18 '18 at 21:00
  • @miradulo The comments and answers here are all helpful. Years ago I programmed in Cobol. I find python to be amazingly expressive! – CopyPasteIt Apr 18 '18 at 21:06
  • @TerryJanReedy Now using `if nxt_page is not None:`. Remember reading about this syntax before, and I am getting more comfortable with it now. – CopyPasteIt Apr 18 '18 at 21:21

1 Answers1

1

The documentation is very clear on how values are evaluated in a boolean context:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

Mureinik
  • 297,002
  • 52
  • 306
  • 350