This coding style bad practise?

Martin P. Hellwig mhellwig at xs4all.nl
Thu May 4 08:55:41 EDT 2006


<cut>

Thanks for the input folks!
I adapted my script to the given suggestions and it's now far more 
'logical', for reference I added it below.

-- 
mph

----- script -----
> import string
> import time
> 
> class IDGenerator(object):
>     """(leading_id, subversion_length, tz) # tz = 'local' or 'gm' (default)
>     Create an ID from a given string, a current datetimestamp and version
>     number which wraps around at given subversion_length.
>     
>     Example usage:
>     >>> id = IDGenerator('01',2)
>     >>> id()
>     '01_20060504_112304_1'
>     >>> id()
>     '01_20060504_112306_2'
>     >>> id()
>     '01_20060504_112307_1'
>     >>> 
>     >>> id = IDGenerator(0005,99) # Note that an int will be cast to a string!
>     >>> id()
>     '5_20060504_112324_01'
>     >>> id()
>     '5_20060504_112327_02'
>     >>> id
>     <class '__main__.IDGenerator'> previous ID is 5_20060504_112324_01 and
>     current ID is 5_20060504_112327_02
>     >>> 
>     
>     """
> 
>     def __init__(self,leading_id, subversion_length, timezone='gm'):
>         self.id = str(leading_id)
>         self.length = int(subversion_length)
>         fill_length = len(str(self.length))
>         self.current = None
>         self.previous = None
>         
>         def fill(number):
>             return(string.zfill(number,fill_length))
>         self.fill = fill
> 
>         if timezone == 'local':
>             self.timeset = time.localtime
>         else:
>             self.timeset = time.gmtime
>             
> 
>     def __call__(self):
>         # If the subversion length has been reached or the generator has not
>         # been defined, (re)define it, otherwise return the next value of the
>         # subversion.
>         try:
>             return_value = self.range_gen.next()
> 
>         except:
>             self.range_gen = ( number for number in range(1,self.length+1) )
>             return_value = self.range_gen.next()
> 
>         # Create the version stamp.
>         return_value = self.id +\
>                        time.strftime("_%Y%m%d_%H%M%S_",self.timeset())+\
>                        self.fill(return_value)
> 
>         # Copy the current ID to the previous and assign a new one to current.
>         self.previous = self.current
>         self.current = return_value
>         
>         # And return it.
>         return(self.current)
> 
>     def __repr__(self):
>         return(str(self.__class__) +
>                ' previous ID is ' +
>                str(self.previous) +
>                ' and current ID is ' +
>                str(self.current))
----- script -----



More information about the Python-list mailing list