I\'ve got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it\'s never seen it before) or otherwise, it appends some letters to make it uni
Well, sorry to say, but you can't just do a direct translation from Perl to Python (including bit-for-bit Perlisms) and expect the outcome to be prettier. It won't be, it will be considerably uglier.
If you want the prettiness of Python you will need to use Python idioms instead.
Now for the question at hand:
from string import uppercase
class Uniquifier(object):
def __init__(self):
self.last_timestamp = None
self.last_suffix = 0
def uniquify(self, timestamp):
if timestamp == self.last_timestamp:
timestamp = '%s%s' % (timestamp,
uppercase[self.last_suffix])
self.last_suffix += 1
else:
self.last_suffix = 0
self.timestamp = timestamp
return timestamp
uniquifier = Uniquifier()
uniquifier.uniquify(a_timestamp)
Prettier? Maybe. More readable? Probably.
Edit (re comments): Yes this fails after Z, and I am altogether unhappy with this solution. So I won't fix it, but might offer something better, like using a number instead:
timestamp = '%s%s' % (timestamp,
self.last_suffix)
If it were me, I would do this:
import uuid
def uniquify(timestamp):
return '%s-%s' % (timestamp, uuid.uuid4())
And just be happy.