Reputation: 6796
I've been reading various python coding style guides, some answers on SO, etc. but none of them mentions some maybe not that important questions, but I would like to know if there is a preferred way for doing this:
In case I have a dictionary, which style would be better to use:
dict_name = {'test': 'somevalue',
'test2': 'other'}
or
dict_name = {
'longer_key': 'somevalue',
'longer_key2': 'other'
}
or
dict_name = {
'test': 'somevalue',
'test2': 'other'
}
or
dict_name = {
'test': 'somevalue',
'test2': 'other'
}
or something else?
Also for when calling methods:
function_name(longer_arg1, longer_arg2, longer_arg3,
longer_arg4)
or
function_name(longer_arg1, longer_arg2, longer_arg3,
longer_arg4)
or
function_name(
longer_arg1,
longer_arg2,
longer_arg3,
longer_arg4
)
or
function_name(
longer_arg1,
longer_arg2,
longer_arg3,
longer_arg4
)
or something else?
when a longer logging line is used, let's say:
loggername.info('this is an awfully long line which must be separated'
'into two lines, am I doing it right? {0}'.format('nope..'))
or even consider this:
loggername.info('this is an {0} {1} line which must be separated'
'into {2} lines, am I doing it right? {0}'.format(
'awfully', 'short', 'three', 'nope..')
)
Now this last is somewhat related to the function calling style too, we have many arguments, a long string, how would be the best to separate these kind of lines?
Upvotes: 3
Views: 1315
Reputation: 143152
You can't go wrong with looking at the PEP 8 - The Style Guide for Python Code for guidance on how to write readable Python code. Highly recommended.
Upvotes: 9
Reputation: 22041
You cannot go wrong with Levon's answer as it is completely objective (though possibly based on a subjective document). PEP 8 should be considered the standard. Answering based on personal bias:
dict_name = {'test': 'somevalue',
'test2': 'other'}
IDLE (Python's Integrated DeveLopment Environment) will format the dictionary this way when hitting return / enter after the first comma. As a result, I often will use this style for large dictionaries.
function_name(longer_arg2, longer_arg2, longer_arg3,
longer_arg4)
Also considering IDLE, the program will indent functions this way if return / enter is pressed after third comma. I usually follow this style, but you will always find occasional exceptions to standard style.
loggername.info('This is an awfully long line which must be separated into two \
lines. Am I doing it right? {}'.format('No.'))
This is probably my most subjective comment. Lines in programs should be 80 or fewer characters long. That should probably apply to both code and text. Remember that you can create block quotes ('''
).
Upvotes: 1