Steven D'Aprano wrote: > On Sat, Oct 02, 2021 at 02:53:03AM -0000, Debashish Palit wrote: > > There is no need of a three_way_flag - just use a conditional > > expression instead of an if-elif-else block, > > Of course you need a three way flag if your function returns a three way > flag. It returns False for ints, True for floats, and None for anything > else. > So the caller needs to handle three cases: > - your function returns True, so call float(s) > - your function returns False, so call int(s) > - your function returns None, so handle the string some other way. > How else could you do it?
Using a conditional expression, we can code it like this: num = float(s) if (c := s.isfloat()) else int(s) if c is False else 0 # any default Better still if we know its going to be a number, we can do - num = float(s) if s.isfloat() else int(s) > > str.isfloat uses the int() and float() functions, > > Correct, which is why your function is wasteful and inefficient. If I > call `isfloat('123')`, the function calls float, and throws the result > away, so I have to call float *again*. So if people use this function, > they are effectively doing: > s = '123.0' # input is a string, from somewhere else > float(s) # throw away the result > num = float(s) str.isfloat does more than just convert to float. Even if you are not converting to a float, str.isfloat is a good check for a valid number. We can simply do - if s.isfloat() is not None: # valid int or float ... _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/5MB37UGHZSHT657B3RL57EW3B5QBEO7T/ Code of Conduct: http://python.org/psf/codeofconduct/