DEV Community

Discussion on: Python beyond PEP8

Collapse
 
j0nimost profile image
John Nyingi

Does this apply to string literals?
lets say you have long strings like

err_obj = {
               "status": 400,
               "error": "images should be in uri format(http://img.png)"
         }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
edelvalle profile image
Eddy Ernesto del Valle Pino

I would write that as:

error = {
   "status": 400,
   "error": "images should be in uri format(http://img.png)"
}
Enter fullscreen mode Exit fullscreen mode

Considerations:

  1. 4 spaces indentation.
  2. Closing bracket at the same level of indentation of the line containing the opening bracket.
  3. Name, err_obj, everything in Python is an object, naming an object "object" does not explains what's the intention or meaning, like naming a view "view" or class "class". So that lefts us with err, and is not much to ask to write a full world: "err" -> "error", specially if this one is short.

Remember we think we are most of the time power typing, but that's not true, in reality most of the time we are reading code, staring into the abyss. Make your code clear, explicit, avoid useless redundancy and don't leave chance for miss interpretation.

Collapse
 
j0nimost profile image
John Nyingi

Thanks I'll make changes to my code.

However, I was asking if you have a really long string e.g. my error object, or a regex string. Is there a way to handle exceptionally long strings without using \ newline ?

Thread Thread
 
edelvalle profile image
Eddy Ernesto del Valle Pino

Yes, you can do something like....

some_stirng = (
    "Bla bla bla bla. "
    "More bla bla bla bla. "
    "More bla bla bla bla"
)

Or use multi-line strings, but usually they are inconvenient because they will get the spaces from the indentation.

Thread Thread
 
edelvalle profile image
Eddy Ernesto del Valle Pino

But keep in mind that this is about taste mostly and subjective, so do what ever you feel fits you and your team...

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
j0nimost profile image
John Nyingi

I agree