开发者

Are there reserved kwargs for python's dict constructor?

When using the kwarg-style dict initialization:

In [3]: dict(a=1, b=2, c=3)
Out[3]: {'a': 1, 'b': 2, 'c': 3}

for some reason, defining the key 'from' raises a syntax error:

In [4]: dict(to=0, from=1)
------------------------------------------------------------
   File "<ipython console>", line 1
     dict(to=0, from=1)
                   ^
SyntaxError: invalid 开发者_开发知识库syntax

What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization?

I am using Python 2.6.


from is used in imports.

Python Language Reference, §2.3.1, "Keywords"

Note that you can still use kwarg expansion to get them through though.


from, like a handful of other tokens, are keywords/reserved words in Python (from specifically is used when importing a few hand-picked objects from a module into the current namespace). You cannot use them as identifiers or anything (ultimately, kwargs are identifiers). It's simply not allowed, even when in theory it could disambiguated, to keep the parser simple and the people writing the parser sane ;)


from is a keyword:

from threading import Thread

Python doesn't have context-sensitive keywords: A name is either a keyword, or can be used as an identifier. There used to be one exception: "as" used to be special-cased in import statements when it was first introduced, but has since been promoted to "full keyword".

Context-sensitive keywords would be a questionable feature. E.g. should

print=3

work or fail (it could be a syntactically incorrect print statement, or an assignment to a variable named print). Or, what about

def print(x):
    print x
print(3)

Should this define a function print? If so, is the last line a call?


you can't use python keywords such as from in kwargs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜