简体   繁体   中英

Best practices for line breaking in python on method declarations and long lists

In a recent code review, it was mentioned that it is better to break parameters for init and other methods onto their own lines because it is easier to read. I have never seen this before and was wondering if this is the pythonic way to handle this scenario.

Parameters on separate lines

 def __init__(
        self,
        name: str = '',
        address: str = '',
        license: str = '',
        job_title: str = '',
        notes: str = '',
        gender: Gender = None,
        status: Status = None
):

Parameters on the same line

def __init__(self, name: str = '', address: str = '', license: str = ''
             job_title: str = '', notes: str = '', 
             gender: Gender = None, status: Status = None):

Following this same pattern, it was also recommended to break up long lists or dictionaries in the same way.

List values on separate lines

countries = [
    Belgium,
    Canada,
    Denmark,
    Ethiopia,
    France, 
    Germany, 
    Haiti, 
    Italy,
    Japan,
    Korea,
    Lebanon
]

List values on the same lines

countries = [Belgium, Canada, Denmark, Ethiopia, France, Germany,     
             Haiti, Italy, Japan, Korea, Lebanon]

I don't think that there is any officially recognized preference here (other than that lines shouldn't go over X characters -- where X = 80 if you're following PEP8 ). Different projects may have different preferences (or no preference) in this area ...

As one point of reference, pylint accepts either of those as valid I think...

My personal preference is to flow the arguments vertically when they don't all fit on one line.

I think that the best "general" advice that I can give you is to try to be consistent with the surrounding code. If you are the first author and the project doesn't have any guidelines, do what you find to be most comfortable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM