Is 'file' a keyword in python?

PythonKeyword

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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!')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3388884View Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonnorthtreeView Answer on Stackoverflow