0

This question is out of itch of being perfect.

I come across the case where I have to get parameter from post and check if it is True or False (in python), and accordingly call the LOC.

Obviously parameter read is of type <str> and if param: always return True.

I had two options now,
1. Convert <str> to <bool> (write own code to convert, or use ast.literal_eval or import from distutils.util import strtobool )
2. Do the string comparison like if param == "True":

The question is what would be the best practice to follow?

1
  • Please Down voters explain the reason. Commented Jun 3, 2016 at 13:31

2 Answers 2

2

I would certainly not go down the route of converting the string to a boolean, that's too much overhead for a simple logic statement. You should first ensure the parameter is either of the values 'True' or 'False'.

Then:

if (param == 'True'):
    # True code here
else:
    # False code here
Sign up to request clarification or add additional context in comments.

1 Comment

You are right, the read <str> parameter has already taken the memory, and converting it to bool will add additional overhead.
0

Memory Considerations:

For String
sys.getsizeof("True")
>> 41
sys.getsizeof("False")
>> 42

For Boolean
sys.getsizeof(True)
>> 24
sys.getsizeof(False)
>> 24

3 Comments

But then you have overhead of converting string to bool as said by @Adam Probert
I am checking the runtime overhead of conversion.. Will post the results after running test.
Well you can use cprofile and check for the runtime difference in your program. Memory wise boolean takes lesser space.

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.