0

I am having difficulties understanding the following block of Python code:

>>> before = None
>>> before = before or str.lower
>>> t = before("Some Text")
>>> t
'some text'

It seems that before is a callable function here (in particular, callable(before) returns True) but I don't understand how this works. Can someone clearly explain the underlying logic? When I read the above block of code, my first though was that before was a ordinary variable. Also, I am wondering if this is considered good coding practice as it's the first time I encounter this particular syntax?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
glpsx
  • 587
  • 1
  • 7
  • 21
  • 4
    `None` is false, so `before` becomes `str.lower`. – Unmitigated Jul 13 '20 at 14:04
  • 2
    No it's not good coding practice. That is poorly written code and should be avoided. – Spencer Wieczorek Jul 13 '20 at 14:07
  • 1
    @Mad Add to duplicates list please: [What does an 'x = y or z' assignment do in Python?](https://stackoverflow.com/q/21566106/4518341) – wjandrea Jul 13 '20 at 14:09
  • 1
    Related: [Assignment with “or” in python](https://stackoverflow.com/q/8747740/4518341) – wjandrea Jul 13 '20 at 14:11
  • 2
    What you are looking at is an antipattern for `str.lower if before is None else before`. See: https://stackoverflow.com/questions/13710631/is-there-shorthand-for-returning-a-default-value-if-none-in-python/13710674 – Niko Föhr Jul 13 '20 at 14:11
  • Conditional expressions were intended to replace the broken practice of using `a and b or c` as a ternary operator. You have bigger design issues regarding how `before` is initialized and/or set if `before = before or str.lower` can behave differently than `before = str.lower if before is None else before`. – chepner Jul 13 '20 at 14:29

0 Answers0