Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

best practices for string constants?

As far as I know, it is usually considered good to extract most strings to constant variables and avoid having "magic" strings and numbers in the middle of code. But in the Python world I have seen Exceptions raised with an string literal most of the time. I have also seen the same done in logging statements, and other similar situations.

Example of raising an Exception with a constant:

ARGUMENT_LIST_TOO_SHORT = "The provided list is too short"

def whatever_function():
    raise ValueError(ARGUMENT_LIST_TOO_SHORT)

Example of raising an Exception with a string literal:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def whatever_function():
    raise ValueError("The provided list is too short")

As I see it, it shouldn’t be too bad if the string is only used once, as the risk of mistyping it is the same as typing it in the constant in the first place.

So is it a good practice to extract error description strings and log strings into constants? Or is it more Pythonic to use string literals?

>Solution :

Think about what you would need to do if you were writing code that was to be executed in a locale where the language didn’t match the fixed text. As far as I know, Python doesn’t having any out-of-the-box concept of a "resource bundle" (unlike Java for example).

This is a matter of opinion but I would argue strongly in favour of saying that text the user sees/interacts with should always be referenced indirectly. Such a technique facilitates re-use and language portability.

Having said that, the original question (and definitely this answer) are opinion based and therefore frowned upon in this forum.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading