skip to Main Content

My VS Code colors the word function distinctively and says it’s a class:

enter image description here

But it behaves like a regular name such as foo. It’s also not a built-in class, as calling it raises a NameError exception.

Does the function word has any special meaning?

3

Answers


  1. Python offers a keyword module that can list both hard and soft keywords present in a language – function is not among them.

    import keyword
    print(keyword.kwlist)
    print(keyword.softkwlist)
    print('function' in (keyword.kwlist + keyword.softkwlist)) # False
    
    Login or Signup to reply.
  2. function is not a reserved word, please see below according to the python documentation, please refer below.

    https://docs.python.org/3/library/keyword.html?highlight=keywords

    https://github.com/python/cpython/blob/3.11/Lib/keyword.py

    This module allows a Python program to determine if a string is a keyword or soft keyword.

    keyword.iskeyword(s)
    Return True if s is a Python keyword.

    Login or Signup to reply.
  3. Here is the list of keywords:

    https://docs.python.org/3/reference/lexical_analysis.html?highlight=keywords#keywords

    Answer is no. You can e.g. use function as an identifier.

    >>> function = 5
    >>> function
    5
    

    E.g. def or if are keywords and you can not do so.

    >>> if = 5
      File "<stdin>", line 1
        if = 5
           ^
    SyntaxError: invalid syntax
    >>> def = 6
      File "<stdin>", line 1
        def = 6
            ^
    SyntaxError: invalid syntax
    

    It is also not a built-in identifier as is e.g. print or map:

    $ python
    Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> function
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'function' is not defined
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search