简体   繁体   English

语法中的空格会影响 Python 的性能吗?

[英]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.显然,这绝不符合 PEP8,我永远不会将这样的东西投入生产,但同时我并不真正知道为什么,我也不真正理解为什么代码在设置时仍然有效,例如这个。 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.我只是想知道为什么这不好的原因。

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.就像任何其他语言一样,您的 python 脚本被编译为字节码,然后由虚拟机解释。 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.逻辑行的结尾由记号 NEWLINE 表示。 Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (eg, between statements in compound statements).语句不能跨越逻辑行边界,除非语法允许 NEWLINE(例如,复合语句中的语句之间)。 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.在 Unix 上,这是 ASCII LF(换行)字符。 On DOS/Windows, it is the ASCII sequence CR LF (return followed by linefeed).在 DOS/Windows 上,它是 ASCII 序列 CR LF(返回后跟换行)。 On Macintosh, it is the ASCII CR (return) character.在 Macintosh 上,它是 ASCII CR(返回)字符。

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

This was an interesting question.这是一个有趣的问题。 Basically the use of white spaces between the operands and the operator is to increase readability.基本上,在操作数和运算符之间使用空格是为了增加可读性。 It's just a matter of personal choice to add one white space or add ten.添加一个空格或添加十个空格只是个人选择的问题。 The interpreter/compiler doesn't care about white spaces.解释器/编译器不关心空格。 It's just about readability.这只是关于可读性。

Now when you do something like this-现在当你做这样的事情 -

a = 10
b = 100
c = a + b 

And when you do something like this-当你做这样的事情时——

a       =          10
b       =          100     
c       =          a + b

You'll notice that the first one is more readable than the second one, but this doesn't mean that the second one is wrong.您会注意到第一个比第二个更具可读性,但这并不意味着第二个是错误的。 It is just a matter of personal choice.这只是个人选择的问题。 Basically the convention says to follow the first method but we would get the same output with or without white spaces.基本上约定说要遵循第一种方法,但我们会得到相同的 output 带或不带空格。

So you may use one or ten white spaces in your program, nobody can question you!!所以你可以在你的程序中使用一个或十个空格,没有人可以质疑你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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