简体   繁体   中英

Python/PyCharm typing: how to cast a list of string to a tuple of float without explicitly casting each value

I have a class method with the following signature:

def UpdateColor(self, color: Tuple[float, float, float]):

I'm trying to call it with arguments coming from a list of strings. I use a list comprehension to cast them to float and then cast the whole list to a tuple:

color = tuple([float(x) for x in args[:3]])

When I'm calling the method with the color variable PyCharm complains about its type:

Expected type 'Tuple[float, float, float]' got 'Tuple[float, ...]' instead

The code analysis can't seem to be able to guess the size of the tuple. I can fix this warning by explicitly casting each string to a float and inserting them into a tuple but it's pretty ugly and will be even worse with more parameters:

color = (float(args[0]), float(args[1]), float(args[2]))

Is there a "good" way to do what I'm trying to do?

I'm using Python 3.7.8 and PyCharm 2021.1.1.

The other two answers (now deleted) offer a pythonic way to do what you want, but won't solve the problem of PyCharm warning you of differing dtype.

Your suggestion of color = (float(args[0]), float(args[1]), float(args[2])) might not be 'strictly' pythonic, but since you are hardcoding the number of arguments you need, I don't see anything wrong with it. With Python not being a statically typed language, sometimes compromises need to be made.

Using NamedTuple

Another nice and pythonic option would be to declare your own NamedTuple .

class YourInput(NamedTuple):
    arg1: float
    arg2: float
    arg3: float


def update_color(arg: YourInput):
    pass

args = [1, 2, 3, 4]
inp = YourInput(*map(float, args[:3]))
update_color(inp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM