简体   繁体   English

为什么不以不正确的方式为字典赋值是错误的?

[英]Why isn't assigning a value to a dictionary in an incorrect way an error?

Look at this simple dictionary:看看这个简单的字典:

d = {'name': 'soroush', 'age': 25}

Suppose I want to assign a new value to d in a wrong way:假设我想以错误的方式为d分配一个新值:

d['aaa']: 'bbb' instead of d['aaa'] = 'bbb' d['aaa']: 'bbb'而不是d['aaa'] = 'bbb'

Python does nothing in this situation...If I print the dictionary I get the same content as before. Python 在这种情况下什么都不做……如果我打印字典,我会得到与以前相同的内容。 I expected to get a syntax error.我预计会出现语法错误。

Isn't it too buggy in a large application and something that python interpreter should warn instead of skipping?在大型应用程序中是不是太错误了,python 解释器应该警告而不是跳过? My second question is, does : cause this to be skipped?我的第二个问题是,是否:会导致跳过?

d = {'name': 'soroush', 'age': 25}
print(d)
d['aaa']: 'bbb'
print(d)

This is not a syntax error or a bug, it's a feature;)这不是语法错误或错误,而是一个特性;)

Python 3.6 added support for type annotations for variables (see PEP 526 for details). Python 3.6 增加了对变量类型注释的支持(详见PEP 526 )。 Example:例子:

x: int = 42

this is pretty redundant, because the type hinting system of python can figure out that 42 is an integer, but there are more useful situations, eg if you want to declare the type of a variable before you assign its contents这是相当多余的,因为 python 的类型提示系统可以确定 42 是 integer,但是还有更多有用的情况,例如,如果您想在分配变量内容之前声明变量的类型

from typing import Optional

x: Optional[str] = None

so, if you do所以,如果你这样做

d: 'bbb'

you declare that variable d is of type 'bbb' , which of course is nonsense, but you can declare it anyways.您声明变量d的类型为'bbb' ,这当然是无稽之谈,但无论如何您都可以声明它。 You can even verify this on your terminal您甚至可以在终端上验证这一点

>>> __annotations__
{'d': 'bbb'}

Now with your actual code现在使用您的实际代码

d['aaa'] : 'bbb'

Here you retrieve the value of key 'aaa' in your dictionary and assign a type to it.在这里,您检索字典中键'aaa'的值并为其分配一个类型。 This doesn't do anything really (check __annotations__ ), but it's still valid syntax.这实际上并没有做任何事情(检查__annotations__ ),但它仍然是有效的语法。

Well it depends on your IDE.好吧,这取决于您的 IDE。 I use VScode and it gave me a underline saying: Type annotation not supported for this type of expression Pylance and also if u want to add a new value to the dict, you can just say:我使用 VScode,它给了我一个下划线: Type annotation not supported for this type of expression Pylance ,如果你想给字典添加一个新值,你可以说:

d = {'name': 'soroush', 'age': 25}
print(d)
d['aaa']= 'bbb'#instead of the colon, add a equal
print(d)

So in total, it depends on your IDE Hope this make sense.所以总的来说,这取决于你的 IDE 希望这是有道理的。

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

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