首页 > 解决方案 > Does whitespace in syntax affect performance in Python?

问题描述

When I'm writing code for a personal project, or if I'm just testing things out, I tend to code like this, just because it makes me happy:

def importcontacts(request):
  context                       = initialize_context(request)
  context['form']               = UploadedFileForm()
  token                         = get_token(request)

  if request.method == 'POST':
    form                        = UploadFileForm(request.POST, request.FILES)

    if form.is_valid():
      contacts                  = request.FILES['file']
      fs                        = FileSystemStorage()
      filename                  = fs.save('import_data.json', contacts)
      uploaded_file_url         = fs.url(filename)
      context['fails']          = ct.import_contacts(uploaded_file_url,
                                                     token,
                                                     context['user']['email'],
                                                     context['user']['name'])
      messages.success(request, 'Contacts imported successfully.')

      return render(request, 'contactsdb/importresult.html', context)

  return render(request, 'contactsdb/import.html', context)

Obviously this isn't in any way PEP8 compliant and I would never put something like this into production but at the same time I don't truly know why and I also don't truly understand why the code even still works when set out like this. I assume all the space makes for slower code?

Googling has not helped me find my answer. I'm not looking for someone to tell me "you should never do that, blah blah", I'm well aware! I'd just like to know the reasons as to why this isn't OK.

标签: pythonpep8

解决方案


Spacing shouldn't slow down code. Much like any other language, your python scripts get compiled to bytecode and then get interpreted by a virtual machine. The parser usually strips comments and whitespace that isn't indentation or a newline. This link further explains how logical lines are treated:

The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.

and this one explains how physical ones are treated:

A physical line ends in whatever the current platform's convention is for terminating lines. On Unix, this is the ASCII LF (linefeed) character. On DOS/Windows, it is the ASCII sequence CR LF (return followed by linefeed). On Macintosh, it is the ASCII CR (return) character.

This link further explains how indentation is treated:

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

And also gives an example of code that is correctly, but strangely indented:

def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r

推荐阅读