Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy should I convert all strings to constants in Python?
    text
    copied!<p>I don't know if this will be useful to the community or not, as it might be unique to my situation. I'm working with a senior programmer who, in his code, has this peculiar habit of turning all strings into constants before using them. And I just don't get why. It doesn't make any sense to me. 99% of the time, we are gaining no abstraction or expressive power from the conversion, as it's done like this:</p> <pre><code>URL_CONVERTER = "url_converter" URL_TYPE_LONG = "url_type_long" URL_TYPE_SHORT = "url_type_short" URL_TYPE_ARRAY = [URL_TYPE_LONG, URL_TYPE_SHORT] for urltype in URL_TYPE_ARRAY: outside_class.validate(urltype) </code></pre> <p>Just like that. As a rule, the constant name is almost always simply the string's content, capitalized, and these constants are seldom referenced more than once anyway. Perhaps less than 5% of the constants thus created are referenced twice or more during runtime.</p> <p>Is this some programming technique that I just don't understand? Or is it just a bad habit? The other programmers are beginning to mimic this (possibly bad) form, and I want to know if there is a reason for me to as well before blindly following.</p> <p>Thanks!</p> <p>Edit: Updated the example. In addition, I understand everyone's points, and would add that this is a fairly small shop, at most two other people will ever see anyone's code, never mind work on it, and these are pretty simple one-offs we're building, not complicated workers or anything. I understand why this would be good practice in a large project, but in the context of our work, it comes across as too much overhead for a very simple task.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload