fedora
fedora

Reputation: 201

Expanding tuple arguments while casting to different types

I've seen different questions about casting while unpacking strucutures of the same type. I.e.

def foo():
    return ('1', '2')

x, y = foo()  # as str
x, y = map(int, foo())  # as int
x, y = [int(n) for n in foo()]  # equivalently as int

But say you had

def foo():
    return ('s', '1')

and you wanted to unpack and cast only the second element of the tuple. Of course there is

x, y = foo()
y = int(y)

which, in the name of simplicity, could definitely be the most pythonic approach. Out of curiosity though, is there an even more succinct way to accomplish the same thing on a single line?

Upvotes: 2

Views: 399

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195438

If you use Python 3.8+, you can use assignment expression :=

def foo():
    return ('s', '1')

x, y = (v:=foo())[0], int(v[1])
print(x, y)

Prints:

s 1

Upvotes: 2

Jab
Jab

Reputation: 27485

You could check if the value is able to be cast to int:

x, y = [int(n) if n.isdigit() for n in foo()]

Although this won't work for negitive numbers so you could use a try/except clause

def convert(s, t=int):
    try:
        return t(s)
    except ValueError:
        return s

x, y = map(convert, foo())

Otherwise if you know every first value will be a str and the second will be int then you can use

x, y = foo(); y = int(y)

If you insist on a 1 liner

Upvotes: 2

Related Questions