__getitem__, __getslice__ question for python 2.2

Ken Seehof kseehof at neuralintegrator.com
Wed May 15 03:16:47 EDT 2002


Eric Max Francis wrote:
> Raymond Hettinger wrote:
> 
> > "logistix" <logstx at bellatlantic.net> wrote
> >
> > > Also, some people don't like to use isinstance, but I'm not sure how
> > > else to
> > > tell if you got an int.
> > 
> > if x != int(x):  print 'expected an integer'
> 
> This is a pretty poor test.  Consider the cases where x is 'a', or when
> it is 2.0.

I don't see the problem.  If x is 'a', x != int(x) evaluates to false,
consistent with 'a' not being an integer.

If x is 2.0, the expression evaluates to true.  People will argue
about whether or not this is correct.  It may or may not be correct,
depending on why you want to constrain x to an integer.  In many
cases it is appropriate to consider 2.0 to be an integer.  It depends
on the context.

If the actual type is important and you don't consider 2.0 to be an
integer, you can say:

  if type(x) != int: ...

or equivalently...

  if type(x) != type(0): ...

- Ken Seehof






More information about the Python-list mailing list