Is `id` a keyword in python?

走远了吗. 提交于 2021-02-07 04:40:06

问题


My editor (TextMate) shows id in an other colour (when used as variable name) then my usual variable names. Is it a keyword? I don't want to shade any keyword...


回答1:


id is not a keyword in Python, but it is the name of a built-in function.

The keywords are:

and       del       from      not       while
as        elif      global    or        with
assert    else      if        pass      yield
break     except    import    print
class     exec      in        raise
continue  finally   is        return
def       for       lambda    try

Keywords are invalid variable names. The following would be a syntax error:

if = 1

On the other hand, built-in functions like id or type or str can be shadowed:

str = "hello"    # don't do this



回答2:


You can also get help from python:

>>> help(id)
Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

or alternatively you can question IPython

IPython 0.10.2   [on Py 2.6.6]
[C:/]|1> id??
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function id>
Namespace:      Python builtin
Docstring [source file open failed]:
    id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)



回答3:


Just for reference purposes:

Check if something is a keyword in Python:

>>> import keyword  
>>> keyword.iskeyword('id')
False

Check all the keywords in Python:

>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
 'while', 'with', 'yield']



回答4:


It's a built in function:

id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)


来源:https://stackoverflow.com/questions/6350847/is-id-a-keyword-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!