109

Is file a keyword in python?

I've seen some code using the keyword file just fine, while others have suggested not to use it and my editor is color coding it as a keyword.

3
  • 3
  • 2
    -1 searching for a list of keywords of a language is both mandatory and natural when trying to learn that language.
    – Solkar
    Jul 24, 2014 at 20:10
  • 9
    @Solkar To which language do you refer? Python2 or Python3? The confusion of OP is reasonable, imo.
    – zero2cx
    Apr 4, 2019 at 15:36

3 Answers 3

148

No, file is not a keyword:

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

The name is not present in Python 3. In Python 2, file is a built-in:

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

It can be seen as an alias for open(), but it was removed in Python 3, where the new io framework replaced it. Technically, it is the type of object returned by the Python 2 open() function.

2
  • 27
    So is it ok to use file as a variable name if I plan to support Python 3 only? Mar 22, 2017 at 6:58
  • 28
    @GustavoBezerra absolutely!
    – Martijn Pieters
    Mar 22, 2017 at 8:27
24

file is neither a keyword nor a builtin in Python 3.

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

file is also used as variable example from Python 3 doc.

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

As others suggested, type in Python 3 it is not defined by default:

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

The color coding in VS Code and possibly other editors probably refers to Python 2, where it is defined by default, it is the type returned by 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'>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.