Beginner: Data type conversion question

Terry Reedy tjreedy at udel.edu
Fri Jan 16 02:35:54 EST 2009


flagg wrote:
> I am still fairly new to python and programming in general.  My
> question is regarding data conversion, I am working on a script that
> will edit dns zone files, one of the functions i wrote handles
> updating the serial number.
> Our zone files use the date as the first part of the serial and a two
> digit integer as the last two.
> 
> i.e. 2009011501.  The next update would be 2009011502, etc
> Here is the function I wrote, I am using dnspython for reading in zone
> files as Zone "objects".  Because dnspython's built-in serial updater
> will not work with how we format our serial's, I have to re-write it.
> 
> def checkSerial():
>     """
>     Checks the current 'date' portion of the serial number and
>     checks the current 'counter'(the two digit number at the end of
>     the serial number), then returns a complete new serial
>     """
>     currentDate =  time.strftime("%Y""%m""%d", time.localtime())
>     for (name, ttl, rdata) in zone.iterate_rdatas(SOA):
>         date = str(rdata.serial)[0:8]
>         inc = str(rdata.serial)[8:10]

If rdate.serial is already a string, as name would imply, the str() call 
is pointless.  If not, can you get inc as int more directly?

>     if date == currentDate:
>         int(inc) + 1
>         print inc
>         newInc = str(inc).zfill(2)
>         serial = date + newInc
>         print "date is the same"
>         return serial
>     elif date < currentDate:
>         newInc = "01".zfill(2)
>         serial = currentDate + newInc
>         print "date is different"
>         return serial
> 
> Through all of this I am doing a lot of data type conversion. string -
>> integer, integer back to string, etc.  Is this an efficient way of
> handling this?  I have to perform basic addition on the "inc"
> variable, but also need to expose that value as a string.   What I
> have above does work, but I can't help but think there is a more
> efficient way. I guess I am not used to data types being converted so
> easily.

Other than that, you are perhaps worrying too much, even if code could 
be squeezed more.  The idea that every object knows how to convert 
itself to a string representation is basic to Python.

tjr




More information about the Python-list mailing list