casting - Python cast string to type if string is not none -
this question has answer here:
i have long list of values cast , assign. each value has possibility of being none. if value none, i'd leave none, otherwise casting. reason being these values end in database , have convert none's null's later.
so far simplest way i've found adding inline if statements each assignment.
self.number = decimal(input.number) if input.number else none
i don't find code appealing, it's lacking in readability , tedious write statements on every input value. prefer decimal(input.number) return none if input.number none doesn't appear case. there simpler way this? suppose make own decimal_ function , call instead?
update:
i've heeded words of advice hear , come this
def dec_(string): if string none: return none else: try: return decimal.decimal(string) except: return none ..... self.number = dec_(input.number)
now need make cast wrapper each type of cast need do.
update2:
i think should work same running try block in dec_
def dec_(string): try: return decimal.decimal(string) except: return none
there no built in way easier you've discovered. writing own function the approved way reduce code duplication , increase readability repeated tasks.
however, note code , description don't quite match up: chr(input.something) if input.something else none
give none
if input.something
falsely value, such 0 or empty string - test explicitly input.something not none
if that's mean.
Comments
Post a Comment