0

I am encountering a weird situation in Python and would like some advice. For some business reasons, we need to keep this python code module to shortest number of lines. Long story --- but it gets into a requirement that this code module is printed out and archived on paper. I didnt make the rules -- just need to pay the mortgage.

We are reading a lot of data from a mainframe web service and applying some business rules to the data. For example and "plain English" business rule would be

If the non resident state value for field XXXXXX is blank or shorter than two character [treat as same], the value for XXXXXX must be set to "NR". Evaluation must treat the value as non resident unless the residence has been explicitly asserted.

I would like to use ternary operators for some of these rules as they will help condense the over lines of code. I have not use ternary's in python3 for this type of work and I am missing something or formatting the line wrong

 mtvartaxresXXX = "NR" if len(mtvartaxresXXX)< 2

does not work.

This block (classic python) does work

if len(mtvartaxresXXX) < 2:
mtvartaxresXXX = "NR"

What is the most "pythonish" way to perform this evaluation on a single line if statement.

Thanks

2
  • 2
    Add the else part as well means what should be the value of mtvartaxresXXX if len(mtvartaxresXXX) >= 2? Commented Feb 3, 2021 at 22:44
  • 1
    Taking this literally, I think the best you'll get is "NR" if len(mtvartaxresXXX) < 2 else mtvartaxresXXX. I'd just use the full if-statement though. Commented Feb 3, 2021 at 22:46

1 Answer 1

1

You can simply write the if statement on a single line:

if len(mtvartaxresXXX) < 2: mtvartaxresXXX = "NR" 

This is the same number of lines as the ternary, and doesn't require an explicit else value, so it's fewer characters.

Sign up to request clarification or add additional context in comments.

2 Comments

Worth mentioning that it's easier to read if you split it over two lines as normal.
He clearly doesn't care about readability, he needs to save lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.