0

I have the following class constructor method:

def __init__(self, diagram, input=None):
        if input == None:
            input = ["b","c","a","d"]
        self.input=input.sort()

However, this gives me None as the value for self.input. Why is using the sort() method leading to the value of None?

khelwood
  • 52,115
  • 13
  • 74
  • 94
  • You want `self.input = sorted(input)`. Or maybe `self.input = input or ["b", "c", "a", "d"]` followed by `self.input.sort()`. – Samwise May 13 '21 at 18:48
  • Thank you, got it ! – Aditya Sharma May 13 '21 at 18:48
  • @Samwise that will also replace `input` with the default if the caller passes an empty list, which may be what OP wants but it's not what the code currently tries to do. – Ryan Haining May 13 '21 at 19:02
  • @AdityaSharma [prefer `is None` to `== None`](https://stackoverflow.com/a/14247419/1013719) – Ryan Haining May 13 '21 at 19:04
  • @Samwise thanks for the reference, interesting read! Also, I tried passing an empty list as the input while calling the method, the result was an empty list and not the default in that case. – Aditya Sharma May 13 '21 at 19:29
  • @AdityaSharma I think you meant to tag me, and I meant with the second suggestion of `self.input = input or ["b", "c", "a", "d"]` like [this example](https://gist.github.com/ryanhaining/4b50a67d50731b1ae29a677175a06fcc) – Ryan Haining May 13 '21 at 19:40
  • @RyanHaining yup I wanted to tag you, sorry about that. Also, you are correct on the output as per the gist. I found the exact term for this: [Null Coalescing](https://en.wikipedia.org/wiki/Null_coalescing_operator) thanks to you. It's one of those things I took for granted and didn't understand till now. – Aditya Sharma May 13 '21 at 20:00
  • @AdityaSharma yeah it would be like null coalescing if the `or` operator only used the latter value for `None`, but since it does all falsy values (like `0`, `""`, `{}`, `[]`) it's not quite that. For a one liner you could do `self.input = input if input is not None else ['b', 'c', 'a', 'd']`. There's [a PEP for getting a `??` operator in python](https://www.python.org/dev/peps/pep-0505/#the-coalesce-rule), no idea if/when it will make it in though. – Ryan Haining May 13 '21 at 20:33
  • @AdityaSharma [you're not the first one to make that mistake](https://www.reddit.com/r/ProgrammerTIL/comments/4ouwng/python_til_pythons_or_is_a_null_coalescing/) – Ryan Haining May 13 '21 at 20:34
  • @RyanHaining yup. It kind of became a de-facto I guess. – Aditya Sharma May 14 '21 at 11:28

0 Answers0