Array destructuring in Python
Asked Answered
C

1

11

I am hoping to make vals in the last line be more clear.

import rx
from rx import operators as op

light_stream = rx.range(1, 10).pipe(
            op.with_latest_from(irradiance_stream),
            op.map(lambda vals: print(vals[0], vals[1])))  # light, irradiance

Is there something like array destructuring like this

op.map(lambda [light, irradiance]: print(light_intensity, irradiance))) # fake

or other ways to make the code clear? Thanks

Carlo answered 1/5, 2019 at 17:33 Comment(2)
You can just use print(*vals). But if you goal is to make your code clear then just use a normal function and assign to local variables light_intensity and irradiance.Neuman
blog.itsyourpal.in/…Contributory
F
8

Python used to allow unpacking of iterable arguments in function signatures, which seems to be what you want for your lambda function. That feature was removed in Python 3, with the reasons set out in PEP 3113.

The main reason it was removed is that it messes up introspection a bit, as there is no good way to name the compound parameter that had been unpacked. If you take a normal parameter (in a normal function, not a one-line lambda), you can achieve the same results with a manual unpacking on a separate line (without messing up the original parameter name):

# def foo(a, (b, c), d):  # this used to be a legal function definition
def foo(a, bc, d):        # but now you must leave the two-valued argument packed up
    b, c = bc             # and explicitly unpack it yourself instead
    ...

Something else that might do what you want though is unpacking of values when you call a function. In your example, you can call print(*vals), and the * tells Python to unpack the iterable vals as separate arguments to print. If vals always has exactly two values, it will be exactly like your current code.

Franchescafranchise answered 1/5, 2019 at 18:33 Comment(1)
big loss in python3.Geelong

© 2022 - 2024 — McMap. All rights reserved.