[Tutor] Force a value to int

Alan Gauld alan.gauld at freenet.co.uk
Thu Apr 13 23:30:28 CEST 2006


> 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



More information about the Tutor mailing list