473,396 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

check if object is number

Is there a good way to determine if an object is a numeric type?
Generally, I avoid type-checks in favor of try/except blocks, but I'm
not sure what to do in this case:

def f(i):
...
if x < i:
...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an
appropriate error.

I thought about calling int() on the value, but this will also allow
some strings (e.g. '1'). I guess this isn't horrible, but it seems
somewhat suboptimal...

Ideas?

Steve
Jul 18 '05 #1
33 25611
Steven Bethard wrote:
Is there a good way to determine if an object is a numeric type?
Generally, I avoid type-checks in favor of try/except blocks, but I'm not sure what to do in this case:

def f(i):
...
if x < i:
...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an
appropriate error.

I thought about calling int() on the value, but this will also allow
some strings (e.g. '1'). I guess this isn't horrible, but it seems
somewhat suboptimal...


How about this?

.... def is_number(x):
.... try:
.... x + 1
.... return True
.... except TypeError:
.... return False

Jul 18 '05 #2
On Fri, 11 Feb 2005 12:11:44 -0700, Steven Bethard
<st************@gmail.com> wrote:
Is there a good way to determine if an object is a numeric type?
Generally, I avoid type-checks in favor of try/except blocks, but I'm
not sure what to do in this case:

def f(i):
...
if x < i:
...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an
appropriate error.
How about:
if type(variable) == type(1):
print "is an integer"
else:
print "please input an integer"

I thought about calling int() on the value, but this will also allow
some strings (e.g. '1'). I guess this isn't horrible, but it seems
somewhat suboptimal...

Ideas?

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #3
Bill Mill wrote:
On Fri, 11 Feb 2005 12:11:44 -0700, Steven Bethard
<st************@gmail.com> wrote:
Is there a good way to determine if an object is a numeric type?


How about:
if type(variable) == type(1):
print "is an integer"
else:
print "please input an integer"


This checks if it is an integer, not if it is a numeric type:

py> x = 1
py> type(x) == type(1)
True
py> # using int instead of type(1)
py> type(x) == int
True
py> x = 1.0
py> type(x) == int
False

Steve
Jul 18 '05 #4
Dan Bishop wrote:
Steven Bethard wrote:
Is there a good way to determine if an object is a numeric type?


How about this?

... def is_number(x):
... try:
... x + 1
... return True
... except TypeError:
... return False


Great, thanks! That's the kind of thing I was looking for!

Steve
Jul 18 '05 #5

"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?
Generally, I avoid type-checks in favor of try/except blocks, but I'm
not sure what to do in this case:

def f(i):
...
if x < i:
...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an
appropriate error.

I thought about calling int() on the value, but this will also allow
some strings (e.g. '1'). I guess this isn't horrible, but it seems
somewhat suboptimal...

Ideas?

Steve


The thing is that python avoids giving a strict definition of what is a 'numeric type', i.e. a
well-defined interface (the same holds for other frequently used interfaces such as 'sequence',
'mapping', 'file-like', etc). It's up to you (the user) to think of all the operations you
anticipate to be supported by each argument, attribute, etc. and define a 'numeric type checker' (or
even better, adaptor) that suits *your application*. In your example, what does your application
consider to be numeric ? Strings are definitely not, integers and floats typically are; on the other
hand, complex numbers are usually not expected, even though mathematically they are 'numeric'. In
this case, you can write something like:
def isNumeric(obj):
# consider only ints and floats numeric
return isinstance(obj,int) or isinstance(obj,float)

The bottom line is that python wisely doesn't enforce any universal numeric type ("in the face of
ambiguity, refuse the temptation to guess").

George
Jul 18 '05 #6
George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?


In your example, what does your application consider to be numeric?


Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior. But I'd rather not specify only those 4
(e.g. with a typecheck), since someone could relatively easily create
their own new numeric type with the same behavior. Do you know a better
way to test for this kind of behavior?

Steve
Jul 18 '05 #7
Steven Bethard wrote:
Is there a good way to determine if an object is a numeric type? Generally, I avoid type-checks in
favor of try/except blocks, but I'm not sure what to do in this case:

def f(i):
...
if x < i:
...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an appropriate error.


assert operator.isNumberType(i)

(but make sure you read the warning in the docs:
http://docs.python.org/lib/module-operator.html )

</F>

Jul 18 '05 #8
As luck would have it, isnumber is a built-in Python function:
isnumber(1) True isnumber(1.0) True isnumber('1')

False

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

Jul 18 '05 #9
Michael Hartl wrote
As luck would have it, isnumber is a built-in Python function:
isnumber(1) True isnumber(1.0) True isnumber('1') False


and what strange Python version would that be?
isnumber(1)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'isnumber' is not defined

</F>

Jul 18 '05 #10

"Michael Hartl" <mh****@post.harvard.edu> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
As luck would have it, isnumber is a built-in Python function:
isnumber(1) True isnumber(1.0) True isnumber('1')

False

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/


Huh ? What python version has this ? Surely not 2.3 and 2.4.

George

Jul 18 '05 #11
> George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?


In your example, what does your application consider to be numeric?


Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior. But I'd rather not specify only those 4
(e.g. with a typecheck), since someone could relatively easily create
their own new numeric type with the same behavior. Do you know a better
way to test for this kind of behavior?

Steve


The problem is more conceptional rather than technical. So what you're saying is that 3 <= "3.0"
should not be allowed, but 3 <= SomeUserDefinedNumericClass(3) is ok, although your program knows
nothing a priori about SomeUserDefinedNumericClass. The idea suggested before, try if "x+1" fails or
not does not get you far; any class that overrides __add__ may fool this test:

class Dummy:
def __add__(self,other):
return 0

Is Dummy 'numeric' ? Probably not. Whether a given instance is "numeric" (or "sequence",
"file-like", etc. for that matter) is a semantic issue. It cannot be resolved by relying on which
methods are supported or not, but what these methods *do*; this is something that no programming
language can tell you now and in the (foreseeable) future.

George
Jul 18 '05 #12
George Sakkis wrote:
George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...

Is there a good way to determine if an object is a numeric type?

In your example, what does your application consider to be numeric?
Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior. But I'd rather not specify only those 4
(e.g. with a typecheck), since someone could relatively easily create
their own new numeric type with the same behavior. Do you know a better
way to test for this kind of behavior?


The problem is more conceptional rather than technical.


Yup.
So what you're saying is that 3 <= "3.0" should not be allowed, but
3 <= SomeUserDefinedNumericClass(3) is ok, although your program knows
nothing a priori about SomeUserDefinedNumericClass. The idea suggested
before, try if "x+1" fails or not does not get you far; any class that
overrides __add__ may fool this test:

class Dummy:
def __add__(self,other):
return 0


Right but by the same logic, we can fool protocols that are builtin to
Python:

py> class C(object):
.... def __iter__(self):
.... return 0
....
py> for x in C():
.... print x
....
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: iter() returned non-iterator of type 'int'

I'm not trying to catch the case where someone is deliberately violating
the protocol. Only the case where they've provided an object that
doesn't conform to the protcol.
Clearly, complex objects don't conform to the protocol I want -- they
don't support comparisons to ints. This is easy to check:

try:
x <= 1
except TypeError:
raise TypeError('%s does not support comparisons to ints' %
type(x).__name__)

Now str objects also don't conform my protocol -- they aren't comparable
to integers in any meaningful sense. Ideally, I should be able to use
the same code as above for str objects (and get a TypeError like "str
objects cannot be compared with int objects"), but unfortunately, the
Python wart of cross-type default comparisons gets in the way. I look
forward to the day when Python 3.0 removes such comparisons. =)

Steve
Jul 18 '05 #13
Fredrik Lundh wrote:
Steven Bethard wrote:
Is there a good way to determine if an object is a numeric type?


assert operator.isNumberType(i)


Interesting, thanks! If I read the source right, PyNumber_Check (which
operator.isNumberType is an alias for) basically just returns True if
the object's type has a __int__ or __float__ method defined:

int
PyNumber_Check(PyObject *o)
{
return o && o->ob_type->tp_as_number &&
(o->ob_type->tp_as_number->nb_int ||
o->ob_type->tp_as_number->nb_float);
}

Did I read that right?

Steve
Jul 18 '05 #14
On Fri, Feb 11, 2005 at 01:17:55PM -0700, Steven Bethard wrote:
George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?


In your example, what does your application consider to be numeric?


Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior. But I'd rather not specify only those 4
(e.g. with a typecheck), since someone could relatively easily create
their own new numeric type with the same behavior. Do you know a better
way to test for this kind of behavior?


Why don't you express just this need as an assertion?

assert 0 <= max <= max + 1, 'Argument must not be zany'

(or whatever error message is suitable)

--
John Lenton (jo**@grulic.org.ar) -- Random fortune:
<Silvrbear> Oxymorons? I saw one yesterday - the pamphlet on "Taco Bell
Nutritional Information"

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (GNU/Linux)

iD8DBQFCDR0DgPqu395ykGsRAsZ0AKCSwEft713brTFzqOkLbk zQPFbfCgCfZPju
ik3e+/fqeqxX3tps6hELGnw=
=ZYYX
-----END PGP SIGNATURE-----

Jul 18 '05 #15
Oops, my bad. The utilities file I use gets loaded automatically when
I start my interpreter, so I mistook isnumber for a built-in function.
A battle-tested isnumber function is defined in Peter Norvig's utils.py
(http://aima.cs.berkeley.edu/python/utils.py):

#def isnumber(x):
# "Is x a number? We say it is if it has an __int__ method."
# return hasattr(x, '__int__')

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

Jul 18 '05 #16
John Lenton wrote:
On Fri, Feb 11, 2005 at 01:17:55PM -0700, Steven Bethard wrote:
George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?

In your example, what does your application consider to be numeric?


Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior. But I'd rather not specify only those 4
(e.g. with a typecheck), since someone could relatively easily create
their own new numeric type with the same behavior. Do you know a better
way to test for this kind of behavior?

Why don't you express just this need as an assertion?

assert 0 <= max <= max + 1, 'Argument must not be zany'


Well a TypeError might be raised in executing the expression:

py> max = complex(0, 1)
py> assert 0 <= max <= max + 1, 'Argument must not be zany'
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=

but I do like the max <= max + 1 idea. Maybe I should do something like:

py> def assertnumber(x):
.... try:
.... 1 < x
.... except TypeError:
.... raise TypeError('%s is not comparable to int' %
.... type(x).__name__)
.... try:
.... if not x <= x + 1:
.... raise TypeError
.... except TypeError:
.... raise TypeError('%s is not monotonic' %
.... type(x).__name__)
....
py> assertnumber(1)
py> assertnumber(1.0)
py> assertnumber(complex(0, 1))
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 5, in assertnumber
TypeError: complex is not comparable to int
py> assertnumber('a')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 11, in assertnumber
TypeError: str is not monotonic
py> class C(object):
.... def __add__(self, other):
.... return 0
.... def __lt__(self, other):
.... return True
....
py> assertnumber(C())
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 11, in assertnumber
TypeError: C is not monotonic

Steve
Jul 18 '05 #17
> > So what you're saying is that 3 <= "3.0" should not be allowed, but
3 <= SomeUserDefinedNumericClass(3) is ok, although your program knows
nothing a priori about SomeUserDefinedNumericClass. The idea suggested
before, try if "x+1" fails or not does not get you far; any class that
overrides __add__ may fool this test:

class Dummy:
def __add__(self,other):
return 0
Right but by the same logic, we can fool protocols that are builtin to
Python:

py> class C(object):
... def __iter__(self):
... return 0
...
py> for x in C():
... print x
...
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: iter() returned non-iterator of type 'int'

I'm not trying to catch the case where someone is deliberately violating
the protocol. Only the case where they've provided an object that
doesn't conform to the protcol.


Note however that in my example there's no TypeError; 0 (or any value for that matter) is perfectly
valid for __add__, while __iter__ must return an iterator.
Clearly, complex objects don't conform to the protocol I want -- they
don't support comparisons to ints. This is easy to check:

try:
x <= 1
except TypeError:
raise TypeError('%s does not support comparisons to ints' %
type(x).__name__)

Now str objects also don't conform my protocol -- they aren't comparable
to integers in any meaningful sense. Ideally, I should be able to use
the same code as above for str objects (and get a TypeError like "str
objects cannot be compared with int objects"), but unfortunately, the
Python wart of cross-type default comparisons gets in the way. I look
forward to the day when Python 3.0 removes such comparisons. =)


Me too... the way comparison works as of now is error-prone, to say the least. Comparing ints with
strings is no more valid than adding them, and python (correctly) raises TypeError for the latter,
but not for the former. For the record, here's the arbitrary and undocumented (?) order among some
main builtin types:
None < 0 == 0.0 < {} < [] < "" < ()

True

George
Jul 18 '05 #18
George Sakkis wrote:
For the record, here's the arbitrary and undocumented (?) order
among some main builtin types:
None < 0 == 0.0 < {} < [] < "" < ()


If you're curious, you can check the source code. Look for
default_3way_compare in object.c. Basically the rundown for dissimilar
types is:

* None is smaller than anything
* Numbers (as defined by PyNumber_Check) are smaller than everything else
* All other types are compared by type name (and by the address of the
type object if the type names are the same).

Pretty arbitrary, yeah. ;)

Steve
Jul 18 '05 #19
Steven Bethard wrote:
Is there a good way to determine if an object is a numeric type? ..
..
..
Ideas?

Maybe this can help?

def isnumber(x):
try:
return(x == x-0)
except:
return False

print '1:\t', isnumber(1)
print '1.25:\t', isnumber(1.25)
print '1.0 / 7:\t', isnumber(1.0 / 7)
print '1+0j:\t', isnumber((1+0j))
print '"spam":\t', isnumber("spam")

output:

1: True
1.25: True
1.0/7: True
1+0j: True
"spam": False

Ooops! While checking other posts I realized that this is almost the
same as Dan Bishop's solution.

Marco
Jul 18 '05 #20
As I mention below, I mistook the function from my utilities file for a
Python built-in; here's the implementation:

#def isnumber(x):
# "Is x a number? We say it is if it has an __int__ method."
# return hasattr(x, '__int__')

Jul 18 '05 #21
marco wrote:
Steven Bethard wrote:
Is there a good way to determine if an object is a numeric type?


Maybe this can help?

def isnumber(x):
try:
return(x == x-0)
except:
return False


Not exactly foolproof:
def isnumber(x): .... try: return (x == x-0)
.... except: return False
.... import numarray
a = numarray.arange(1.1, 5.5)
a array([ 1.1, 2.1, 3.1, 4.1, 5.1]) print '%s:\t' % a, isnumber(a) [ 1.1 2.1 3.1 4.1 5.1]: [1 1 1 1 1]

The result is actually this:
a == a-0 array([1, 1, 1, 1, 1], type=Bool)

And if you try to call bool() on it (as perhaps
your isnumber() routine already should have, rather
than relying on == to return a boolean):
bool(a == (a-0))

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\a\python24\Lib\site-packages\numarray\generic.py", line 477, in
__nonzero__
raise RuntimeError("An array doesn't make sense as a truth value. Use
sometrue(a) or alltrue(a).")
RuntimeError: An array doesn't make sense as a truth value. Use sometrue(a) or
alltrue(a).

Yuck.

Of course, most of the other definitions of "is a number" that
have been posted may likewise fail (defined as not doing what the
OP would have wanted, in this case) with a numarray arange.
Or maybe not. (Pretty much all of them will call an arange a
number... would the OP's function work properly with that?)

-Peter
Jul 18 '05 #22
Peter Hansen wrote:
Of course, most of the other definitions of "is a number" that
have been posted may likewise fail (defined as not doing what the
OP would have wanted, in this case) with a numarray arange.
Or maybe not. (Pretty much all of them will call an arange a
number... would the OP's function work properly with that?)


No, but it will fail properly since my code basically looks like:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So if max is an array, though all of the proposed isnumber checks will
call it a number, my code will (rightly) fail when the array (n <= max)
gets __nonzero__ called in the while condition. I guess I'd prefer it
to fail in the isnumber check, but overall, I'm more concerned that
_some_ error is produced, not necessarily which one. (I'm also not
thrilled that bool(array) raises a RuntimeError instead of a TypeError...)

Steve
Jul 18 '05 #23
Steven Bethard wrote:
Peter Hansen wrote:
Of course, most of the other definitions of "is a number" that
have been posted may likewise fail (defined as not doing what the
OP would have wanted, in this case) with a numarray arange.
Or maybe not. (Pretty much all of them will call an arange a
number... would the OP's function work properly with that?)

No, but it will fail properly since my code basically looks like:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So if max is an array, though all of the proposed isnumber checks will
call it a number, my code will (rightly) fail when the array (n <= max)
gets __nonzero__ called in the while condition. I guess I'd prefer it
to fail in the isnumber check, but overall, I'm more concerned that
_some_ error is produced, not necessarily which one. (I'm also not
thrilled that bool(array) raises a RuntimeError instead of a TypeError...)

Steve

Steve,

How about explicitly calling an adapter in your function, e.g.?
def f(max=None):
max = number(max)
while max is None or n <= max:
...
# complicated incrementing of n


then you can define number to document the required behavior and return more
useful exceptions if the object fails. At the same time, anyone who wants to
use a custom number class with your function has a ready-made unittest.
def number(obj): ... """Adapts obj to be numeric, or fails helpfully"""
... if isinstance(obj, (int, float, long, )): # these types conform
... return obj
... elif isinstance(obj, basestring): # these types have a known adaptation
... return int(obj)
... else: # check the object exhibits the required behavior
... try:
... assert obj+1 >= 1
... except Exception, err:
... raise TypeError, "obj does not support addition and comparisons
with numbers (%s)" % err
... return obj
... class MyNumber(object): ... def __init__(self, data):
... self.data = data
... def __add__(self, other):
... return MyNumber(self.data + other)
... def __cmp__(self, other):
... return self.data.__cmp__(other)
... a = MyNumber(42)
a is number(a) True
number(1+2j) Traceback (most recent call last):
File "<input>", line 1, in ?
File "<input>", line 11, in number
TypeError: obj does not support addition and comparisons with numbers (cannot
compare complex numbers using <, <=, >, >=) number(array.array("i",[1])) Traceback (most recent call last):
File "<input>", line 1, in ?
File "<input>", line 11, in number
TypeError: obj does not support addition and comparisons with numbers (can only
append array (not "int") to array)


Cheers
Michael

Jul 18 '05 #24
Michael Spencer wrote:
Steven Bethard wrote:
Peter Hansen wrote:
Of course, most of the other definitions of "is a number" that
have been posted may likewise fail (defined as not doing what the
OP would have wanted, in this case) with a numarray arange.


How about explicitly calling an adapter in your function, e.g.?


Yup, that's basically what I'm doing right now. The question was really
how to define that adapter function. =)

Steve
Jul 18 '05 #25
Steven Bethard wrote:
Michael Spencer wrote:
Steven Bethard wrote:
Peter Hansen wrote:

Of course, most of the other definitions of "is a number" that
have been posted may likewise fail (defined as not doing what the
OP would have wanted, in this case) with a numarray arange.

How about explicitly calling an adapter in your function, e.g.?

Yup, that's basically what I'm doing right now. The question was really
how to define that adapter function. =)

Steve

OK - then my entry is:
assert obj+1 >= 1
:-)

Michael

Jul 18 '05 #26
Le vendredi 11 Février 2005 20:11, Steven Bethard a écrit*:
Is there a good way to determine if an object is a numeric type?
Generally, I avoid type-checks in favor of try/except blocks, but I'm
not sure what to do in this case:

def f(i):
...
if x < i:
...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an
appropriate error.
This is a very bad Python feature that might very well be fixed in version 3.0
according to your own reply to a previous thread. This problem clearly shows
that this Python feature does hurt.

Here's a transcript of the answer :
Yes, that rule being to compare objects of different types by their type
names (falling back to the address of the type object if the type names
are the same, I believe). *Of course, this is arbitrary, and Python does
not guarantee you this ordering -- it would not raise backwards
compatibility concerns to, say, change the ordering in Python 2.5.
What was the goal behind this rule ?


I believe at the time, people thought that comparison should be defined
for all Python objects. *Guido has since said that he wishes the
decision hadn't been made this way, and has suggested that in Python
3.0, objects of unequal types will not have a default comparison.

Probably this means ripping the end off of default_3way_compare and
raising an exception. *As Fredrik Lundh pointed out, they could, if they
wanted to, also rip out the code that special-cases None too.

Steve


Regards

Francis Girard
Jul 18 '05 #27
Op 2005-02-11, Steven Bethard schreef <st************@gmail.com>:
George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?


In your example, what does your application consider to be numeric?


Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior.


Actually no, floats don't meet this behaviour or more specifically
floats don't guarantee this behaviour. It depends of course on
your implementation of f, but it is possible with floats to keep
incrementing and never reach a maximum.

--
Antoon Pardon
Jul 18 '05 #28
Antoon Pardon wrote:
Op 2005-02-11, Steven Bethard schreef <st************@gmail.com>:
George Sakkis wrote:
"Steven Bethard" <st************@gmail.com> wrote in message
news:gc********************@comcast.com...
Is there a good way to determine if an object is a numeric type?

In your example, what does your application consider to be numeric?


Well, here's the basic code:

def f(max=None):
...
while max is None or n <= max:
...
# complicated incrementing of n

So for 'max', technically all I need is <= support. However, the code
also depends on the fact that after incrementing 'n' enough, it will
eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
will all meet this behavior.


Actually no, floats don't meet this behaviour or more specifically
floats don't guarantee this behaviour. It depends of course on
your implementation of f, but it is possible with floats to keep
incrementing and never reach a maximum.


My code won't hit this corner case. I'm incrementing with integers.

Steve
Jul 18 '05 #29
Steven Bethard wrote:
Actually no, floats don't meet this behaviour or more specifically
floats don't guarantee this behaviour. It depends of course on
your implementation of f, but it is possible with floats to keep
incrementing and never reach a maximum.


My code won't hit this corner case. I'm incrementing with integers.


incrementing what with integers?
f = 9007199254740992.0
f == f+1

True

</F>

Jul 18 '05 #30
Fredrik Lundh wrote:
Steven Bethard wrote:
Actually no, floats don't meet this behaviour or more specifically
floats don't guarantee this behaviour. It depends of course on
your implementation of f, but it is possible with floats to keep
incrementing and never reach a maximum.


My code won't hit this corner case. I'm incrementing with integers.

incrementing what with integers?
>>> f = 9007199254740992.0
>>> f == f+1

True


I mean that the number that's being incremented is an integer:

py> f = 9007199254740992.0
py> i = 9007199254740991
py> i <= f
True
py> i += 1
py> i <= f
True
py> i += 1
py> i <= f
False

Steve
Jul 18 '05 #31
On Sat, 12 Feb 2005 16:01:26 -0800, rumours say that Michael Spencer
<ma**@telcopartners.com> might have written:
Yup, that's basically what I'm doing right now. The question was really
how to define that adapter function. =)

Steve

OK - then my entry is:
assert obj+1 >= 1
:-)


So -1 is not a number.
--
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
Jul 18 '05 #32
Christos TZOTZIOY Georgiou wrote:
On Sat, 12 Feb 2005 16:01:26 -0800, rumours say that Michael Spencer
<ma**@telcopartners.com> might have written:

Yup, that's basically what I'm doing right now. The question was really
how to define that adapter function. =)

Steve


OK - then my entry is:
assert obj+1 >= 1
:-)

So -1 is not a number.

At least not a legal one for Steven's function as I understood it

Michael

Jul 18 '05 #33
Michael Spencer wrote:
Christos TZOTZIOY Georgiou wrote:
On Sat, 12 Feb 2005 16:01:26 -0800, rumours say that Michael Spencer
<ma**@telcopartners.com> might have written:
OK - then my entry is:
assert obj+1 >= 1
:-)


So -1 is not a number.


At least not a legal one for Steven's function as I understood it


No, -1 is still a "number" for my particular case.

Basically, I want "numbers" to be valid upper bounds to an increasing
sequence of integers. This means that "numbers" must be comparable to
integers and must behave properly as upper bounds to integers. More
formally:

If n is a "number" (in my particular sense), then there exists an
integer i such that i > n, and for all integers i such that i > n and
for all positive integers x, i + x > n.

STeVe
Jul 18 '05 #34

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: olskar | last post by:
How can I check the number of values in an array and echo them in my PHP script?
14
by: ankitmathur | last post by:
Hi, I'm facing a pretty peculiar problem. In one of my pages I print the number of rows depending upon the number of Qty I got filled in my previous page i.e. If Qty is filled in as 3 in...
4
by: JBiggsCC | last post by:
I have a very simple login page which takes an ID number via a HTML form GET. What is easiest way to check that ID number against an Access DB to see if it exists? I want to redirect with the...
4
by: Mark Berry | last post by:
Hi, I'm working on my "last resort" error block for a web application. If the error occurs after a Request has been made, I want to show the URL. If the Request object is not available, I'll...
4
by: Aaryan123 | last post by:
Function to check a number between a range in perl ========================================= Back ground: This situation has been fixed in Perl5.005. Use of .. in a for loop will iterate over...
5
by: veki | last post by:
Hello, What shoud I change in this code to check, if some number is december: #include <iostream> #include <stdio.h> using namespace std; int main(){
0
by: Edwin.Madari | last post by:
updated creature running in its own thread will get you started. try it foryourself, change sleep times per your need. import os, sys, threading, time class Creature: def __init__(self,...
1
by: Raman Pahwa | last post by:
plz tell me how to check the number of open connections in ASP code.
2
HaLo2FrEeEk
by: HaLo2FrEeEk | last post by:
I need to check if a given number is an int or a double. I don't want to round doubles to ints, I just want to know if the number is an int or a double. Is there any way to do this? For the...
7
by: ismailc | last post by:
Good day, I thought i had this sorted but it does not seem to check if the object is undefined / not created. I'm trying to check if object is undefined & i tried a few methos but no luck...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.