-3

New to python and trying to understand what does following syntax doing ?

  def testMissingConfig(self):
        """ if config is missing, the config is valid """

        input_args = self.buildmock()

        validation_errors = [
            x
            for x in self.validator.validate(
                ValidatorArguments(input_args=input_args)
            )
            if x
        ]
        validation_keys = {x.key for x in validation_errors}
        self.assertEmpty(validation_keys)

Especially the array initialization for "validation_errors"

Amber
  • 1,229
  • 9
  • 29

1 Answers1

0

It is called List comprehension. Here you can combine assignments, loops, functions all in one block.

One of the big advantages of list comprehension is that they allow developers to write less code that is often easier to understand.

Syntax:

[expression for item in list]

Example:

number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)

Here the numberlist loops over 0 to 20 and gives even numbers 0,2,4...20 as result.

Similarly in your code, validation_errors will store x if x exists(not null)

Lambda functions can also be used to create and modify lists in less lines of code.

Reference: https://www.programiz.com/python-programming/list-comprehension