Re: [Tutor] Force a value to int

2006-04-13 Thread Alan Gauld
> Is there a particular way to force a value to be an int by either
> converting it with int() or returning a default value.

I don't think it exists.
I think that would be a difficult thing to do in a generic way.
The potential for inadvertant data loss is very high. 

> I've ended up writing my own function to do it, 

I assume you mean something like:

def forceInt(v, default=42):
   try: result = int(v)
   except: result = default
   return result

but if you do 

class C: # lots of stuff in here
pass
c = C()

v=forceInt(c)

You could lose all the data in C.
I suppose that if you make the default non defaulted - so you have 
to provide a default - that would be better, the default could then 
be the object itself

v = forceInt(c,c)

Is that what you mean?

Alan G

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Force a value to int

2006-04-13 Thread Kent Johnson
Ed Singleton wrote:
> Is there a particular way to force a value to be an int by either
> converting it with int() or returning a default value.
> 
> I've ended up writing my own function to do it, but it seems like the
> kind of thing that would be built-in somewhere.

No, there is no built-in for this but it's easy to write your own:

def my_int(value, default):
   try:
 return int(value)
   except ValueError:
 return default

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Force a value to int

2006-04-13 Thread Ed Singleton
Is there a particular way to force a value to be an int by either
converting it with int() or returning a default value.

I've ended up writing my own function to do it, but it seems like the
kind of thing that would be built-in somewhere.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor