Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cast string to type if string is not none [duplicate]

I have a long list of values to cast and assign. Each value has the possibility of being None. If the value is None, I'd like to leave it as None, otherwise do the casting. The reason being that these values will end up in a database and I will have to convert the None's to NULL's later.

So far the simplest way I've found to do this is by adding inline if statements to each assignment.

self.number = Decimal(input.number) if input.number else None

I don't find the code very appealing, it's lacking in readability and it will be tedious to write those statements on for every input value. I would prefer that Decimal(input.number) just return None if input.number is None but that doesn't appear to be the case. Is there a simpler way to do this? I suppose I could make my own Decimal_ function and call that instead?


Update:

I've heeded the words of advice hear and come up with this

def dec_(string):
    if string is None:
        return None
    else:
        try:
            return decimal.Decimal(string)
        except:
            return None
.....

self.number = dec_(input.number)

Now I just need to make a cast wrapper for each type of cast I will need to do.


Update2:

I think it should work the same by simply running the try block in dec_

def dec_(string):
    try:
        return decimal.Decimal(string)
    except:
        return None
like image 627
user3817250 Avatar asked Dec 03 '25 12:12

user3817250


1 Answers

There is no built in way to do this that is easier than what you've already discovered. But writing your own function is the approved way to reduce code duplication and increase readability for repeated tasks.

However, do note that your code and your description don't quite match up: chr(input.something) if input.something else None will give you None if input.something is any falsely value, such as 0 or the empty string - test explicitly for input.something is not None if that's what you mean.

like image 156
lvc Avatar answered Dec 06 '25 02:12

lvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!