Assume I have this (currently return-less) function:
def codepoint_convert(text, offset):
codepoint = text[offset]
if codepoint <= 0x01:
output = "\n"
elif codepoint >= 0x09 and codepoint <= 0x12: # digits
output = chr(0x30 + (codepoint-0x09))
elif codepoint >= 0x13 and codepoint <= 0x2C: # uppercase letters
output = chr(0x41 + (codepoint-0x13))
elif codepoint >= 0x2D and codepoint <= 0x46: # lowercase letters
output = chr(0x61 + (codepoint-0x2D))
elif codepoint >= 0x47 and codepoint <= 0x62: # multi-byte codepoints
offset += 1
codepoint = (codepoint << 8) + text[offset]
output = cp_dict[codepoint]
else:
print("Invalid codepoint at 0x%08X" % offset)
offset += 1
How would I best update (i.e. increment and append, respectively) both offset and output in a while loop defined like this?:
def main():
text = "\x0A\x0B\x0C\x01"
offset = 0
output = ''
while offset < len(text):
I have previously used two approaches:
1
def convert_codepoint(text, offset, output):
# A: see first code snippet
# B: concatenate to "output" (+=) instead of assigning (=)
return [offset, output]
def main():
text = "\x0A\x0B\x0C\x01"
offset = 0
output = ''
while offset < len(text):
offset, output = convert_codepoint(text, offset, output)
2
offset = 0 # global variable
def convert_codepoint(text, offset):
global offset
# A: see first code snippet
return output
def main():
text = "\x0A\x0B\x0C\x01"
output = ''
while offset < len(text):
output += convert_codepoint(text, offset)
To me, the first approach is confusing, because it looks like it replaces the offset and output variables instead of updating them, since it uses = instead of += (it does not seem like I could somehow use += in a list-assignment in Python 3.4.2 anyway, since it throws a SyntaxError ("illegal expression for augmented assignment")). And the use of a list as a return value does not seem so port-friendly either.
My gripe with the second approach is that it uses a global variable. I want it to be possible to call convert_codepoint() (e.g. if the script is imported as a module) without having to have a global variable defined. The offset variable may need to be re-initialized from the main function, too, so that could get messy.
Any other approach I could try, to update the variables locally, in a nice and clear way?
update_codepointorget_updated_outputor some such thing.