SantoshGupta7
SantoshGupta7

Reputation: 6197

Setting python variable with conditional statement

I came across this line of code

ax = ax or plt.gca()

It is line 29 here

https://github.com/Santosh-Gupta/adjustText/blob/master/adjustText/init.py

How exactly does this expression work?

Upvotes: 0

Views: 179

Answers (3)

ShellAddicted
ShellAddicted

Reputation: 159

ax will assume the result of the or operation between ax and result of plt.gca()
see Wikipedia for details.

Explaination

you can understand line 29 as a way to give a fallback value to ax,
if ax is passed as function parameter (so it's not None) passed value will be assigned to ax,
otherwise (ax is None) plt.gca() will be assigned to ax
because results of None OR plt.gca() is plt.gca() anything it will returns.

you can see line 29 as: ax = ax if ax is not None else plt.gca()

Upvotes: 3

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27271

If the first operand evaluates to True, the expression evaluates to the first operand:

>>> True or "second"
True

>>> "first" or "second"
"first"

If the first operand evaluates to False, the expression evaluates to the second operand:

>>> False or "second"
"second"

>>> 0 or "second"
"second"

>>> None or "second"
"second"

Here are some values that evaluate to the same as False:

False
0
None
""
[]
{}    

So, in the line:

ax or plt.gca()

If ax is None, the expression evaluates to the second operand, plt.gca().

>>> None or plt.gca()
plt.gca()

Upvotes: 0

J. Katzwinkel
J. Katzwinkel

Reputation: 1943

In the scope of line 29 of the code you refer to, ax is a function parameter that default to None.

def get_text_position(text, ax=None): #28
    ax = ax or plt.gca()              #29
    [...]                             #30

The assignment of ax or plt.gca() to ax is meant to ensure that the value of ax is not None for the remainder of the function scope. If the function is being called with a non-None value for the ax parameter, the line has no effect, as evaluation of the expression to the right stops at the or, which is already satisfied by its left operand not being None. If no ax parameter gets passed to the function, or if it is explicitly set to None, evaluation of ax or plt.gca() results in the return value of the latter, as ax, being None, does not satisfy the expression, hence the remainder after the or must cover for it. matplotlib's documentation indicates that its method that gets called in this case in line 29 will ensure to return a none-null object.

So long story short, the or operator is applicable not only to boolean operands, but works the same way with None and non-None values, as it does with False and True.

Upvotes: 0

Related Questions