[Python-ideas] `numbers.Natural`
Ethan Furman
ethan at stoneleaf.us
Fri Sep 26 23:12:34 CEST 2014
On 09/26/2014 02:04 PM, David Mertz wrote:
> On Fri, Sep 26, 2014 at 1:57 PM, Thomas Gläßle <t_glaessle at gmx.de <mailto:t_glaessle at gmx.de>> wrote
>
> And more importantly: you wouldn't expect isNatural(3.5) to return True.
>
>
> That's not a problem with my one-liner, nor Ian's:
>
>>>> isNatural = lambda x: int(x)==x and x>0
>>>> isNatural(3.5)
> False
>
> However, my correction to avoid crashing on some inputs is still wrong, given:
>
>>>> isinstance(0j, numbers.Number)
> True
>>>> int(0j)
> TypeError
>
> So I think I really need a couple lines:
>
> def isNatural(x):
> try:
> return int(x)==x and x>0
> except (TypeError, ValueError):
> return False
If we had PEP 463 [1] it could still be a one-liner ;)
def is_natural(x):
return int(x) == x and x > 0 except TypeError, ValueError: False
--
~Ethan~
[1] http://legacy.python.org/dev/peps/pep-0463/
More information about the Python-ideas
mailing list