1

I am struggling a bit with the concept of Lambda expressions and I have this piece of code here:

nav.add_branch(
'containers_pods',
{
    'containers_pod':
    [
        lambda ctx: list_tbl.select_row_by_cells(
            {'Name': ctx['pod'].name, 'Provider': ctx['provider'].name}),
        {
            'containers_pod_edit_tags':
            lambda _: pol_btn('Edit Tags'),
        }
    ],
    'containers_pod_detail':
    [
        lambda ctx: list_tbl.click_row_by_cells(
            {'Name': ctx['pod'].name, 'Provider': ctx['provider'].name}),
        {
            'containers_pod_timelines_detail':
            lambda _: mon_btn('Timelines'),
            'containers_pod_edit_tags_detail':
            lambda _: pol_btn('Edit Tags'),
        }
    ]
}

)

Can somebody please explain me the usage of the Lambda expression here? More of this code is here:

https://github.com/ManageIQ/integration_tests/blob/093f4cf42127e2f98cc01d91fc2d4db487543ca1/cfme/containers/pod.py#L11-L35

Thanks!

blong
  • 2,815
  • 8
  • 44
  • 110
Pavel Zagalsky
  • 1,620
  • 7
  • 22
  • 52

1 Answers1

1

Lambdas are anonymous functions, mentally you can replace this block

[
    lambda ctx: list_tbl.select_row_by_cells(
        {'Name': ctx['pod'].name, 'Provider': ctx['provider'].name}),
    {
        'containers_pod_edit_tags':
        lambda _: pol_btn('Edit Tags'),
    }
]

with

def function_1(ctx):
    return list_tbl.select_row_by_cells(
        {'Name': ctx['pod'].name, 'Provider': ctx['provider'].name}
    )

def function_2(_):
    return pol_btn('Edit Tags')


[
    function_1,
    {
        'containers_pod_edit_tags':
        function_2,
    }
]

The underscore _ in lambda _: is a convention in Python for variables you're not going to use, a "throwaway", as you can see that lambda/function is not using the argument _.

Community
  • 1
  • 1
bakkal
  • 54,350
  • 12
  • 131
  • 107