On Sat, Oct 02, 2021 at 01:21:46PM -0000, Debashish Palit wrote:
> 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,
> 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
Here is your three_way_flag:
c := s.isfloat()
Just because you called it the obfuscated name "c" (for character?)
instead of a meaningful name, doesn't change the fact that it is a flag
that can take three values, or that you have to use *two* conditional
tests giving *three* branches to deal with it.
We could write it as a lookup table with a dispatch function too:
num = {True: float, False: int, None: lambda x: 0}[s.isfloat()](s)
There are still three possible values for your flag, and three possible
actions to take.
> Better still if we know its going to be a number, we can do -
But you don't know it is going to be a number.
> We can simply do -
> if s.isfloat() is not None: # valid int or float
> ...
And then what? Is it a float or an int?
if s.isfloat() is not None:
if s.isfloat():
return float(s)
else:
return int(s)
else:
return 0
It's still a three way flag even if you calculate the flag twice. That
just makes it even more wasteful and inefficient.
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/64RPLQID2PLBUHTAN4BJCZ747DZPKRVX/
Code of Conduct: http://python.org/psf/codeofconduct/