file'是Python中的关键字吗?

112 投票
3 回答
37736 浏览
提问于 2025-04-18 14:39

在Python中,file是个关键字吗?

我看到有些代码中使用了file这个词,没问题;但也有人建议不要用它,而且我的编辑器把它标记成了关键字。

3 个回答

2

正如其他人所提到的,在Python 3中,type这个东西默认是没有定义的:

Python 3.8.10 (default, Nov 14 2022, 12:59:47) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined

在VS Code和可能其他编辑器中的颜色编码,可能是指Python 2,在那个版本中,type默认定义的,它是由open()返回的类型:

Python 2.7.18 (default, Jul  1 2022, 12:27:04) 
[GCC 9.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> file
<type 'file'>
25

filePython 3 中既不是一个 关键字 也不是一个 内置函数

>>> import keyword
>>> 'file' in keyword.kwlist
False
>>> import builtins
>>> 'file' in dir(builtins)
False

file 还被用作 Python 3 中的变量示例,具体可以参考 文档

with open('spam.txt', 'w') as file:
    file.write('Spam and eggs!')
151

不,file 不是一个关键字:

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

在 Python 3 中,这个名字是不存在的。在 Python 2 中,file 是一个内置的东西:

>>> import __builtin__, sys
>>> hasattr(__builtin__, 'file')
True
>>> sys.version_info[:2]
(2, 7)

它可以看作是 open() 的一个别名,但在 Python 3 中被移除了,取而代之的是新的 io 框架。从技术上讲,它是 Python 2 中 open() 函数返回的对象类型

撰写回答